var User = require("./user");
var dao = require("./../dao/dao");
let shopping_dao = require("./../dao/shopping_dao");
var redis_dao = require("./../dao/redis_dao");
var crypto = require('crypto');
var fs = require('fs');
var ServerInfo = require('./../config/ServerInfo').getInstand;
var activityConfig = require('./../config/activityConfig');
var Post = require('./post');
var urlencode = require('urlencode');
var schedule = require("node-schedule");
var log = require("./../../util/loginfo").getInstand;
var async = require('async');
var updateConfig = require('./updateConfig').getInstand;
var RobotConfig = require('./../config/RobotConfig');
var ml_api = require('./ml_api');

var redis_laba_win_pool = require("./../../util/redis_laba_win_pool");
var redis_send_and_listen = require("./../../util/redis_send_and_listen");

var landlord_race_dao = require('./../dao/landlord_race_Dao');
const ThreadSafeLoginList = require('./login_list');

// 引入线程安全的 UserList
const ThreadSafeUserList = require('./user_list');

var GameInfo = function () {
    var _gameinfo = "";
    var Game = function () {

        //初始化游戏
        this.init = function () {

            //初始化用户列表 - 使用线程安全版本
            this.userList = new ThreadSafeUserList();
            //在线人数为0
            this.onlinePlayerCount = 0;
            //机器人数量
            this.onlineRobotCount = 0;
            //统计
            this.winTotal = 0;
            //维护模式
            this.maintain = false;

            this._loginList = new ThreadSafeLoginList();

            this.gameRank = {};

            this.tempuserList = {};

            this.sendCardList = {};

            this.score_changeLogList = [];

            this.diamond_changeLogList = [];

            this.sendApiList = [];

            this.lineOutList = {};

            this.server_log_list = [];
            var self = this;
            dao.selectServerLog(function (Result, rows) {
                if (Result) {
                    self.server_log_list = rows
                }
            });

            this.landload_race_is_start = false;
            this.landload_race_dict = {};

            this.landload_race_sort = {};

            this.checkNo = {};

            this._io = {};

            this.gm_socket = {};   //gm登录socket

            this.test = false;

            this.todayId = 0;

            //初始化redis
            redis_laba_win_pool.redis_win_pool_init();

            var rule = new schedule.RecurrenceRule();
            var times = [];
            for (var i = 0; i < 60; i++) {
                times.push(i);
            }
            rule.second = times;
            var c = 0;
            var self = this;
            var j = schedule.scheduleJob(rule, function () {
                if (self.maintain) {
                    --gameConfig.maintainTime;
                    if (!gameConfig.maintainTime) {
                        self.disconnectAllUser();
                    }
                }

                var nowDate = new Date();
                var now_hours = nowDate.getHours();
                var minute = nowDate.getMinutes();
                var second = nowDate.getSeconds();
                self.game_second = second;

                if (second % 35 == 0) {
                    self.userList.cleanupInactiveUsers()
                }

                if (second == 0) {    //彩金推送
                    redis_laba_win_pool.get_redis_win_pool().then(async function (data) {
                        try {
                            const userIds = await self.userList.getAllUserIds();
                            for (const userId of userIds) {
                                const user = await self.userList.getUser(userId);
                                if (user && user._socket) {
                                    user._socket.emit("RedisWinPool", data);
                                }
                            }
                        } catch (error) {
                            log.err("彩金推送错误: " + error.message);
                        }
                    });
                }

                if (now_hours == 5) {
                    this.sendCardList = {};
                }

                if (now_hours == 23 && minute == 0 && second == 0) {    //斗地主比赛场统计
                    var start_time = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate() + " " + "11:00:00";
                    var end_time = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate() + " " + "23:00:00";
                    start_time = start_time.substring(0, 19);
                    start_time = start_time.replace(/-/g, '/');

                    end_time = end_time.substring(0, 19);
                    end_time = end_time.replace(/-/g, '/');

                    var new_start_time = new Date(start_time).getTime();
                    var new_end_time = new Date(end_time).getTime();
                    landlord_race_dao.query_race_record_for_sort({
                        start_time: new_start_time,
                        end_time: new_end_time
                    }, function (state, rows) {
                        if (state) {
                            var race_user_list = [];
                            var race_user_dict = {};
                            for (var r in rows) {
                                if (race_user_list.indexOf(rows[r].uid) == -1) {
                                    race_user_list.push(rows[r].uid);
                                    if (rows[r].iswin) {
                                        race_user_dict[rows[r].uid] = { play: 1, win: 1 }
                                    } else {
                                        race_user_dict[rows[r].uid] = { play: 1, win: 0 }
                                    }
                                    race_user_dict[rows[r].uid]["nick_name"] = rows[r].nick_name;
                                    race_user_dict[rows[r].uid]["head_url"] = rows[r].head_url

                                } else {
                                    if (race_user_dict[rows[r].uid]["play"] < 20) {
                                        race_user_dict[rows[r].uid]["play"] += 1;
                                        if (rows[r].iswin) {
                                            race_user_dict[rows[r].uid]["win"] += 1;
                                        }
                                    }
                                }
                            }

                            for (var rud in race_user_dict) {
                                if (race_user_dict[rud]["play"] < 20) {
                                    delete race_user_dict[rud]
                                }
                            }

                            log.info("---------------------------")
                            log.info(race_user_dict)

                            var race_win_res_dict = {};
                            var res_rac_index_list = [];
                            for (var rud in race_user_dict) {
                                var win_key = parseFloat((parseInt(race_user_dict[rud]["win"]) / parseInt(race_user_dict[rud]["play"])).toFixed(4)) * 100;
                                race_win_res_dict[rud] = win_key;
                                res_rac_index_list.push(win_key)
                            }


                            var new_res_rac_index_list = es6_set(JSON.parse(JSON.stringify(res_rac_index_list)));
                            new_res_rac_index_list.sort(function (a, b) {
                                return a - b
                            })
                            new_res_rac_index_list.reverse();


                            var win_1 = null;
                            var win_2 = null;
                            var win_3 = null;
                            var win_4 = [];

                            if (new_res_rac_index_list.length) {
                                win_1 = new_res_rac_index_list[0];
                                if (new_res_rac_index_list.length > 1) {
                                    win_2 = new_res_rac_index_list[1];
                                }
                                if (new_res_rac_index_list.length > 2) {
                                    win_3 = new_res_rac_index_list[2];
                                }

                                if (new_res_rac_index_list.length > 3) {
                                    for (var i = 3; i < new_res_rac_index_list.length; i++) {
                                        if (new_res_rac_index_list[i] && i < 10) {
                                            win_4.push(new_res_rac_index_list[i])
                                        }

                                    }
                                }
                            }
                            var huojianguser = [];
                            var win_list_1 = [];
                            var win_list_2 = [];
                            var win_list_3 = [];
                            var win_list_4 = [];
                            //一等奖
                            for (var rwr in race_win_res_dict) {
                                if (race_win_res_dict[rwr] == win_1) {
                                    win_list_1.push({
                                        user_id: rwr,
                                        nick_name: race_user_dict[rwr].nick_name,
                                        head_url: race_user_dict[rwr].head_url,
                                        sheng_lv: win_1,
                                    })
                                }
                                if (race_win_res_dict[rwr] == win_2) {
                                    win_list_2.push({
                                        user_id: rwr,
                                        nick_name: race_user_dict[rwr].nick_name,
                                        head_url: race_user_dict[rwr].head_url,
                                        sheng_lv: win_2,
                                    })
                                }
                                if (race_win_res_dict[rwr] == win_3) {
                                    win_list_3.push({
                                        user_id: rwr,
                                        nick_name: race_user_dict[rwr].nick_name,
                                        head_url: race_user_dict[rwr].head_url,
                                        sheng_lv: win_3,
                                    })
                                }
                                if (win_4.indexOf(race_win_res_dict[rwr]) > -1) {
                                    win_list_4.push({
                                        user_id: rwr,
                                        nick_name: race_user_dict[rwr].nick_name,
                                        head_url: race_user_dict[rwr].head_url,
                                    })
                                }

                            }
                            //发奖
                            var pw_award1 = parseInt(self.landload_race_dict.pw_award1);   //冠军
                            var pw_award2 = parseInt(self.landload_race_dict.pw_award2); //亚军
                            var pw_award3 = parseInt(self.landload_race_dict.pw_award3); //季军
                            var pw_award4 = parseInt(self.landload_race_dict.pw_award4);//4-10
                            var pw_award5 = parseInt(self.landload_race_dict.pw_award5);  //其他人


                            var score_1 = pw_award1;
                            var score_2 = pw_award2;
                            var score_3 = pw_award3;
                            var score_4 = pw_award4;
                            var score_5 = pw_award5;

                            if (win_list_1.length) {
                                score_1 = pw_award1 / win_list_1.length;
                            }
                            if (win_list_2.length) {
                                score_2 = pw_award2 / win_list_2.length;
                            }
                            if (win_list_3.length) {
                                score_3 = pw_award3 / win_list_3.length;
                            }
                            if (win_list_4.length) {
                                score_4 = pw_award4 / win_list_4.length;
                            }

                            // 使用线程安全的方式更新用户分数
                            for (var wl in win_list_1) {
                                var r_userInfo = {
                                    sendUserId: win_list_1[wl].user_id,
                                    sendCoin: score_1,
                                    change_type: 0,
                                    diamond: 0
                                };
                                self.GameBalance(r_userInfo);
                                huojianguser.push(win_list_1[wl].user_id)
                            }
                            for (var wl in win_list_2) {
                                var r_userInfo = {
                                    sendUserId: win_list_2[wl].user_id,
                                    sendCoin: score_2,
                                    change_type: 0,
                                    diamond: 0
                                };
                                self.GameBalance(r_userInfo);
                                huojianguser.push(win_list_2[wl].user_id)
                            }
                            for (var wl in win_list_3) {
                                var r_userInfo = {
                                    sendUserId: win_list_3[wl].user_id,
                                    sendCoin: score_3,
                                    change_type: 0,
                                    diamond: 0
                                };
                                self.GameBalance(r_userInfo);
                                huojianguser.push(win_list_3[wl].user_id)
                            }
                            for (var wl in win_list_4) {
                                var r_userInfo = {
                                    sendUserId: win_list_4[wl].user_id,
                                    sendCoin: score_4,
                                    change_type: 0,
                                    diamond: 0
                                };
                                self.GameBalance(r_userInfo);
                                huojianguser.push(win_list_4[wl].user_id)
                            }

                            for (var rud in race_user_dict) {
                                if (huojianguser.indexOf(rud) == -1) {
                                    var r_userInfo = { sendUserId: rud, sendCoin: score_5, change_type: 0, diamond: 0 };
                                    self.GameBalance(r_userInfo);
                                }
                            }

                            self.landload_race_sort = {
                                win_list_1: win_list_1,
                                win_list_2: win_list_2,
                                win_list_3: win_list_3,
                                win_list_4: win_list_4,
                                score_1: score_1,
                                score_2: score_2,
                                score_3: score_3,
                                score_4: score_4,
                                score_5: score_5,
                            };

                            log.info("斗地主比赛场排位---------------------")
                            log.info(self.landload_race_sort)
                        }
                    });
                }
            });
        };

        this.disconnectAllUser = async function () {
            try {
                const userIds = await this.userList.getAllUserIds();
                for (const userId of userIds) {
                    const user = await this.userList.getUser(userId);
                    if (user && user._socket) {
                        user._socket.disconnect();
                    }
                }
                log.info("服务器开启维护，已经全部离线");
            } catch (error) {
                log.err("断开所有用户连接错误: " + error.message);
            }
        };

        this.setIo = function (_io) {
            this._io = _io;
        };

        this.setGMSocket = function (_gm, _socket) {
            this.gm_socket[_gm] = _socket;
        };

        this.Setmaintain = function (_flag) {
            this.maintain = _flag;
        };

        this.isMaintain = function () {
            return this.maintain;
        };

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = async function (socket) {
            if (socket.userId) {
                const user = await this.userList.getUser(socket.userId);
                return user ? user.Islogin() : false;
            } else {
                return false;
            }
        };

        //添加用户
        // this.addUser = function (userInfo, socket, callback_a) {
        //     log.info("添加用户:" + userInfo.Id);

        //     var newDate = new Date();
        //     var key = "slezz;e3";
        //     var md5 = crypto.createHash('md5');
        //     var content = userInfo.Id + userInfo.score + newDate + key;
        //     var sign = md5.update(content).digest('hex');
        //     userInfo.sign = sign;

        //     //在没有添加用户之前找到道具列表
        //     var self = this;
        //     async.waterfall([
        //         function (callback) {
        //             dao.getPropByUserId(userInfo.Id, function (result, row) {
        //                 //log.info(userInfo.Id + "获取道具");
        //                 if (result) {
        //                     var proplist = {};
        //                     for (var i = 0; i < row.length; i++) {
        //                         proplist[row[i].propid] = row[i].propcount;
        //                     }
        //                     userInfo.propList = proplist;
        //                 } else {
        //                     userInfo.propList = {};
        //                 }

        //                 // 使用线程安全的方式添加用户
        //                 self.userList.addUser(userInfo, socket, userInfo.Robot)
        //                     .then((user) => {
        //                         var resultObj = {
        //                             account: user._account,
        //                             id: user._userId,
        //                             nickname: user._nickname,
        //                             score: user._score,
        //                             sign: user._sign,
        //                             proplist: user._proList,
        //                             headimgurl: user._headimgurl,
        //                             diamond: user._diamond,
        //                             giftTicket: user._giftTicket,
        //                             phoneNo: user._phoneNo,
        //                             official: user._official,
        //                             isVip: user.is_vip,
        //                             totalRecharge: user.totalRecharge,
        //                         };
        //                         log.info(`[game] getPropByUserId user ${userInfo.Id} isRobot ${user._Robot} sign ${user._sign}`);
        //                         result = { resultid: 1, msg: 'login succeed!', Obj: resultObj };
        //                         callback(null, result);
        //                     })
        //                     .catch((err) => {
        //                         log.err("添加用户到线程安全列表失败: " + err.message);
        //                         callback(err);
        //                     });
        //             });
        //         },
        //         function (result, callback) {
        //             //log.info(userInfo.Id + "金币");
        //             dao.getScore(userInfo.Id, function (Result, rows) {
        //                 if (Result) {
        //                     self.userList.getUser(userInfo.Id).then((user) => {
        //                         if (user) {
        //                             user._diamond = rows.diamond;
        //                             user._giftTicket = rows.giftTicket;
        //                             user._score = rows.score;
        //                             result.Obj.score = rows.score;
        //                             result.Obj.diamond = rows.diamond;
        //                             result.Obj.giftTicket = rows.giftTicket;
        //                             log.info(`[game] getScore user ${userInfo.Id} isRobot ${user._Robot} score ${user._score} diamond ${user._diamond} giftTicket ${rows.giftTicket}`);
        //                         }
        //                         callback(null, result);
        //                     });
        //                 } else {
        //                     callback(null, result);
        //                 }
        //             });
        //         },
        //         function (result, callback) {
        //             dao.LoginaddTempScore(userInfo.Id, function (Result, rows) {
        //                 if (Result) {
        //                     self.userList.getUser(userInfo.Id).then((user) => {
        //                         if (user) {
        //                             for (var i = 0; i < rows.length; ++i) {
        //                                 var youScore = user._score;
        //                                 user._score += rows[i].score;
        //                                 result.Obj.score += rows[i].score;
        //                                 var youNowScore = user._score;

        //                                 var userInfolog = {
        //                                     userid: userInfo.Id,
        //                                     score_before: youScore,
        //                                     score_change: rows[i].score,
        //                                     score_current: youNowScore,
        //                                     change_type: rows[i].change_type,
        //                                     isOnline: false
        //                                 };
        //                                 self.score_changeLogList.push(userInfolog);
        //                             }
        //                             log.info(`[game] LoginaddTempScore user ${userInfo.Id} isRobot ${user._Robot} rows length ${rows.length}`);
        //                         }
        //                         callback(null, result);
        //                     });
        //                 } else {
        //                     callback(null, result);
        //                 }
        //             });
        //         },
        //         function (result, callback) {
        //             dao.LoginaddTempDiamond(userInfo.Id, function (Result, rows) {
        //                 if (Result) {
        //                     self.userList.getUser(userInfo.Id).then((user) => {
        //                         if (user) {
        //                             for (var i = 0; i < rows.length; ++i) {
        //                                 var youScore = user._diamond;
        //                                 user._diamond += rows[i].score;
        //                                 result.Obj.diamond += rows[i].score;
        //                                 var youNowScore = user._diamond;

        //                                 var userInfolog = {
        //                                     userid: userInfo.Id,
        //                                     diamond_before: youScore,
        //                                     diamond_change: rows[i].score,
        //                                     diamond_current: youNowScore,
        //                                     change_type: rows[i].change_type,
        //                                     isOnline: false
        //                                 };
        //                                 self.diamond_changeLogList.push(userInfolog);
        //                             }
        //                             log.info(`[game] LoginaddTempDiamond user ${userInfo.Id} isRobot ${user._Robot} rows length ${rows.length}`);
        //                         }
        //                         callback(null, result);
        //                     });
        //                 } else {
        //                     callback(null, result);
        //                 }
        //             });
        //         },
        //         function (result, callback) {
        //             redis_laba_win_pool.get_redis_win_pool().then(function (data) {
        //                 result.win_pool = data;
        //                 socket.emit('loginResult', result);

        //                 log.info("[game] redis_laba_win_pool user " + userInfo.Id + " isRobot " + userInfo.Robot);
        //                 callback(null);
        //             });
        //         }
        //     ], function (err, result) {
        //         if (err) {
        //             log.err(err);
        //             log.info(result);
        //             callback_a(0);
        //         } else {
        //             self.userList.getUser(userInfo.Id).then((user) => {
        //                 if (user) {
        //                     log.info(userInfo.Id + "登录分数" + user._score);
        //                     log.info(userInfo.Id + "登录钻石" + user._diamond);
        //                     user.loginEnd = true;

        //                     socket.emit('ServerListResult', { GameInfo: ServerInfo.getServerAll() });
        //                     self.getSendPrize(userInfo.Id, function (result) {
        //                         socket.emit('prizeListResult', { prizeList: result });
        //                     });

        //                     //发送每日活动信息
        //                     self.getdaySendPrize(userInfo.Id, function (result) {
        //                         socket.emit('dayListResult', {
        //                             nowday: result.nowday,
        //                             getcoin: result.getcoin,
        //                             unclaimedList: result.list
        //                         });
        //                     });

        //                     //是否有首次兑换
        //                     self.getfirstexchange(userInfo.Id, function (result) {
        //                         socket.emit('firstExchagerResult', {
        //                             firstExchager: result.firstexchange,
        //                             zhifubao: result.zhifubao,
        //                             zhifubaoName: result.zhifubaoName
        //                         });
        //                     });

        //                     //发送等级信息
        //                     self.getLv(userInfo.Id, function (result) {
        //                         socket.emit('lv', result);
        //                     });

        //                     //发送是否在房间信息
        //                     var linemsg = self.getLineOutMsg(userInfo.Id);
        //                     log.info("linemsg == ", JSON.stringify(linemsg));
        //                     if (linemsg.Result && linemsg.tableId != -1 && linemsg.seatId != -1) {
        //                         socket.emit('lineOutMsg', {
        //                             gameId: linemsg.gameId,
        //                             serverId: linemsg.serverId,
        //                             tableId: linemsg.tableId,
        //                             seatId: linemsg.seatId,
        //                             tableKey: linemsg.tableKey
        //                         });
        //                         //self.lineOutSet({userId:userInfo.Id})
        //                     }

        //                     socket.emit('noticeMsg', self.server_log_list);

        //                     // 获取实时统计信息
        //                     self.userList.getStats().then((stats) => {
        //                         log.info("online user number is ", stats.players + " robot num " + stats.robots);
        //                     });
        //                 }
        //                 callback_a(1);
        //             });
        //         }
        //     });
        // };

        this.addUser = function (userInfo, socket, callback_a) {
            log.info("添加用户:" + userInfo.Id);

            var newDate = new Date();
            var key = "slezz;e3";
            var md5 = crypto.createHash('md5');
            var content = userInfo.Id + userInfo.score + newDate + key;
            var sign = md5.update(content).digest('hex');
            userInfo.sign = sign;

            // 添加超时机制
            var timeout = setTimeout(function () {
                log.err("addUser 操作超时，用户ID: " + userInfo.Id);
                callback_a(0);
            }, 30000); // 30秒超时

            var cleanup = function () {
                clearTimeout(timeout);
            };

            // 在没有添加用户之前找到道具列表
            var self = this;
            async.waterfall([
                function (callback) {
                    dao.getPropByUserId(userInfo.Id, function (result, row) {
                        if (result) {
                            var proplist = {};
                            for (var i = 0; i < row.length; i++) {
                                proplist[row[i].propid] = row[i].propcount;
                            }
                            userInfo.propList = proplist;
                        } else {
                            userInfo.propList = {};
                        }

                        // 使用线程安全的方式添加用户
                        self.userList.addUser(userInfo, socket, userInfo.Robot)
                            .then(function (user) {
                                var resultObj = {
                                    account: user._account,
                                    id: user._userId,
                                    nickname: user._nickname,
                                    score: user._score,
                                    sign: user._sign,
                                    proplist: user._proList,
                                    headimgurl: user._headimgurl,
                                    diamond: user._diamond,
                                    giftTicket: user._giftTicket,
                                    phoneNo: user._phoneNo,
                                    official: user._official,
                                    isVip: user.is_vip,
                                    totalRecharge: user.totalRecharge,
                                };
                                log.info('[game] getPropByUserId user ' + userInfo.Id + ' isRobot ' + user._Robot + ' sign ' + user._sign);
                                var result = { resultid: 1, msg: 'login succeed!', Obj: resultObj };
                                callback(null, result);
                            })
                            .catch(function (err) {
                                log.err("添加用户到线程安全列表失败: " + err.message);
                                callback(err);
                            });
                    });
                },
                function (result, callback) {
                    dao.getScore(userInfo.Id, function (Result, rows) {
                        if (Result) {
                            self.userList.getUser(userInfo.Id).then(function (user) {
                                if (user) {
                                    user._diamond = rows.diamond;
                                    user._giftTicket = rows.giftTicket;
                                    user._score = rows.score;
                                    result.Obj.score = rows.score;
                                    result.Obj.diamond = rows.diamond;
                                    result.Obj.giftTicket = rows.giftTicket;
                                    log.info('[game] getScore user ' + userInfo.Id + ' isRobot ' + user._Robot + ' score ' + user._score + ' diamond ' + user._diamond + ' giftTicket ' + rows.giftTicket);
                                }
                                callback(null, result);
                            }).catch(function (error) {
                                log.err("getUser 失败: " + error.message);
                                callback(null, result); // 继续流程，不中断
                            });
                        } else {
                            callback(null, result);
                        }
                    });
                },
                function (result, callback) {
                    dao.LoginaddTempScore(userInfo.Id, function (Result, rows) {
                        if (Result) {
                            self.userList.getUser(userInfo.Id).then(function (user) {
                                if (user) {
                                    for (var i = 0; i < rows.length; ++i) {
                                        var youScore = user._score;
                                        user._score += rows[i].score;
                                        result.Obj.score += rows[i].score;
                                        var youNowScore = user._score;

                                        var userInfolog = {
                                            userid: userInfo.Id,
                                            score_before: youScore,
                                            score_change: rows[i].score,
                                            score_current: youNowScore,
                                            change_type: rows[i].change_type,
                                            isOnline: false
                                        };
                                        self.score_changeLogList.push(userInfolog);
                                    }
                                    log.info('[game] LoginaddTempScore user ' + userInfo.Id + ' isRobot ' + user._Robot + ' rows length ' + rows.length);
                                }
                                callback(null, result);
                            }).catch(function (error) {
                                log.err("getUser 失败: " + error.message);
                                callback(null, result);
                            });
                        } else {
                            callback(null, result);
                        }
                    });
                },
                function (result, callback) {
                    dao.LoginaddTempDiamond(userInfo.Id, function (Result, rows) {
                        if (Result) {
                            self.userList.getUser(userInfo.Id).then(function (user) {
                                if (user) {
                                    for (var i = 0; i < rows.length; ++i) {
                                        var youScore = user._diamond;
                                        user._diamond += rows[i].score;
                                        result.Obj.diamond += rows[i].score;
                                        var youNowScore = user._diamond;

                                        var userInfolog = {
                                            userid: userInfo.Id,
                                            diamond_before: youScore,
                                            diamond_change: rows[i].score,
                                            diamond_current: youNowScore,
                                            change_type: rows[i].change_type,
                                            isOnline: false
                                        };
                                        self.diamond_changeLogList.push(userInfolog);
                                    }
                                    log.info('[game] LoginaddTempDiamond user ' + userInfo.Id + ' isRobot ' + user._Robot + ' rows length ' + rows.length);
                                }
                                callback(null, result);
                            }).catch(function (error) {
                                log.err("getUser 失败: " + error.message);
                                callback(null, result);
                            });
                        } else {
                            callback(null, result);
                        }
                    });
                },
                function (result, callback) {
                    redis_laba_win_pool.get_redis_win_pool().then(function (data) {
                        result.win_pool = data;
                        socket.emit('loginResult', result);

                        log.info("[game] redis_laba_win_pool user " + userInfo.Id + " isRobot " + userInfo.Robot);
                        callback(null);
                    }).catch(function (error) {
                        log.err("获取redis彩金池失败: " + error.message);
                        callback(null); // 继续流程，彩金池失败不影响登录
                    });
                }
            ], function (err, result) {
                cleanup(); // 清理超时定时器

                if (err) {
                    log.err("addUser waterfall 错误: " + (err.message || err));
                    callback_a(0);
                } else {
                    self.userList.getUser(userInfo.Id).then(function (user) {
                        if (user) {
                            log.info(userInfo.Id + "登录分数" + user._score);
                            log.info(userInfo.Id + "登录钻石" + user._diamond);
                            user.loginEnd = true;

                            socket.emit('ServerListResult', { GameInfo: ServerInfo.getServerAll() });
                            self.getSendPrize(userInfo.Id, function (result) {
                                socket.emit('prizeListResult', { prizeList: result });
                            });

                            //发送每日活动信息
                            self.getdaySendPrize(userInfo.Id, function (result) {
                                socket.emit('dayListResult', {
                                    nowday: result.nowday,
                                    getcoin: result.getcoin,
                                    unclaimedList: result.list
                                });
                            });

                            //是否有首次兑换
                            self.getfirstexchange(userInfo.Id, function (result) {
                                socket.emit('firstExchagerResult', {
                                    firstExchager: result.firstexchange,
                                    zhifubao: result.zhifubao,
                                    zhifubaoName: result.zhifubaoName
                                });
                            });

                            //发送等级信息
                            self.getLv(userInfo.Id, function (result) {
                                socket.emit('lv', result);
                            });

                            //发送是否在房间信息
                            var linemsg = self.getLineOutMsg(userInfo.Id);
                            log.info("linemsg == ", JSON.stringify(linemsg));
                            if (linemsg.Result && linemsg.tableId != -1 && linemsg.seatId != -1) {
                                socket.emit('lineOutMsg', {
                                    gameId: linemsg.gameId,
                                    serverId: linemsg.serverId,
                                    tableId: linemsg.tableId,
                                    seatId: linemsg.seatId,
                                    tableKey: linemsg.tableKey
                                });
                            }

                            socket.emit('noticeMsg', self.server_log_list);

                            // 获取实时统计信息
                            self.userList.getStats().then(function (stats) {
                                log.info("online user number is ", stats.players + " robot num " + stats.robots);
                            }).catch(function (error) {
                                log.err("获取统计信息失败: " + error.message);
                            });
                        }
                        callback_a(1);
                    }).catch(function (error) {
                        log.err("最终获取用户失败: " + error.message);
                        callback_a(0);
                    });
                }
            });
        };

        this.logintime = async function (_id) {
            const user = await this.userList.getUser(_id);
            if (user) {
                return user.logincheck(new Date());
            }
            return 1;
        };

        //获得在线人数
        this.getOnlinePlayerCount = async function () {
            const stats = await this.userList.getStats();
            return stats.players;
        };

        //在线所有人
        this.getOnlinePlayer = async function () {
            // 注意：这个方法返回的是线程安全的 userList 对象
            const stats = await this.userList.getStats();
            return stats.players + stats.robots;
        };

        //在线机器人数量
        this.getOnlineRobotCount = async function () {
            const stats = await this.userList.getStats();
            return stats.robots;
        };

        this.setCleanGameIdByUserId = async function (_userinfo) {
            if (_userinfo.userId) {
                log.info(_userinfo.userId + "清除游戏ID");
                const user = await this.userList.getUser(_userinfo.userId);
                if (user) {
                    user.resetGame();
                    log.info("游戏ID" + user.getGameId());
                }
            }
        };

        //删除用户
        this.deleteUser = async function (_userinfo) {
            if (_userinfo.userId) {
                const user = await this.userList.getUser(_userinfo.userId);
                if (user && !user.getGameId() && !user.deleteFlag && !user._Robot) {
                    log.info("用户" + _userinfo.userId + "删除!");

                    var score_change = _userinfo.userScore - user._score;
                    var score_before = user._score;
                    user.deleteFlag = true;
                    this.tempuserList[_userinfo.userId] = user;

                    if (_userinfo.userScore != null) {
                        this.tempuserList[_userinfo.userId]._score = _userinfo.userScore;
                        if (!_userinfo.nolog) {
                            var info = {
                                userid: _userinfo.userId,
                                score_before: score_before,
                                score_change: score_change,
                                score_current: _userinfo.userScore,
                                change_type: (_userinfo.gameId + 10),
                                isOnline: true,
                                ChannelType: user._ChannelType
                            };
                            this.score_changeLogList.push(info);
                        }
                    }

                    var diamond_change = _userinfo.userDiamond - user._diamond;
                    var diamond_before = user._diamond;
                    if (_userinfo.userDiamond != null) {
                        this.tempuserList[_userinfo.userId]._diamond = _userinfo.userDiamond;

                        dao.AddDiamondSub({
                            userid: _userinfo.userId,
                            diamond: diamond_change,
                            change_type: 2,
                        }, function (result_u) {
                            if (result_u) {
                                log.info("钻石修改成功 用户:", _userinfo.userId);
                            } else {
                                log.err("钻石修改失败 用户:", _userinfo.userId);
                            }
                        });

                        //储存玩家游戏钻石变化量
                        if (!_userinfo.nolog) {
                            var info = {
                                userid: _userinfo.userId,
                                diamond_before: diamond_before,
                                diamond_change: diamond_change,
                                diamond_current: _userinfo.userDiamond,
                                change_type: (_userinfo.gameId + 10),
                                isOnline: true,
                                ChannelType: user._ChannelType
                            };
                            this.diamond_changeLogList.push(info);
                        }
                    }

                    // 从主用户列表中删除
                    await this.userList.removeUser(_userinfo.userId);
                }
            }
        };

        this.deleteUserNoLoginGame = async function (userid, flag) {
            const user = await this.userList.getUser(userid);
            if (user) {
                if (!user.getGameId() && !user._ageinLogin) {
                    await this.userList.removeUser(userid);
                    log.info("情况1,未登录游戏离线!");
                    return;
                }

                if (flag) {
                    await this.userList.removeUser(userid);
                    log.info("情况2,未登录游戏离线!");
                }
            }
        };

        this.GameUpdateGold = async function (_info) {
            //俱乐部扣除群主房卡用
            if (_info.sendUserId) {
                if (_info.diamond > 0 && _info.sendCoin <= 0) {
                    var userInfo = {
                        sendUserId: _info.sendUserId,
                        sendCoin: 0,
                        change_type: _info.change_type,
                        diamond: _info.diamond
                    };
                    this.GameBalance(userInfo, function (state) {
                        if (state) {
                            log.info("user: " + _info.sendUserId + " diamond: " + _info.diamond + " change_type " + _info.change_type);
                        }
                    });
                } else if (_info.sendCoin > 0 && _info.diamond <= 0) {
                    var userInfo = {
                        sendUserId: _info.sendUserId,
                        sendCoin: _info.sendCoin,
                        change_type: _info.change_type,
                        diamond: 0
                    };
                    this.GameBalance(userInfo, function (state) {
                        if (state) {
                            log.info("user: " + _info.sendUserId + " gold: " + _info.sendCoin + " change_type " + _info.change_type);
                        }
                    });
                } else {
                    // var userInfo = {sendUserId: _info.sendUserId, sendCoin: 0, change_type: 0, diamond: _info.diamond};
                    // this.GameBalanceSub(userInfo, function (_sendStr) {
                    //     log.info("创建房间 房卡扣除2 群主:", _info.sendUserId, _info.diamond)
                    //     log.info(_sendStr)
                    // });
                    log.info("暂时保留！");
                }
            } else {
                log.err("game update gold send user is null ");
            }
        };

        //获得用户当前分数
        this.getUserscore = async function (_userId) {
            const user = await this.userList.getUser(_userId);
            return user ? user._score : 0;
        };

        //获得用户
        this.getUser = async function (_userId) {
            return await this.userList.getUser(_userId);
        };

        this.getUserTicket = async function (_userId, callback) {
            const user = await this.userList.getUser(_userId);
            if (user) {
                callback(user._giftTicket);
            } else {
                dao.getScore(_userId, function (Result, rows) {
                    if (Result) {
                        callback(rows.giftTicket);
                    } else {
                        callback(-1);
                    }
                });
            }
        };

        //获得用户
        this.webGetUser = function (_account, callback) {
            var format = {};
            if (_account) {
                dao.webGetUser(_account, function (code, result) {
                    format.code = code;
                    format.nickname = result.nickname;
                    format.ticket = result.giftTicket;
                    format.userId = result.userId;
                    callback(format);
                })
            } else {
                callback(format);
            }
        }

        //商城购买
        this.shopBuy = async function (_userId, _productId, _count, callback) {
            //获得商品配置
            var shopConfig = updateConfig.getShopConfig();
            if (!shopConfig[_productId]) {
                callback(2);
                return;
            }

            var self = this;

            //拿到实效商品券
            this.getUserTicket(_userId, function (giftTicket) {
                if (giftTicket == -1) {
                    callback(5);
                    return;
                }

                if (shopConfig[_productId].price > giftTicket) {
                    //礼品券不足
                    callback(1);
                    return;
                }

                //购买成功
                self.userList.getUser(_userId).then((user) => {
                    if (user) {
                        user._giftTicket -= shopConfig[_productId].price;
                        callback(0);
                    } else {
                        //去修改数据库
                        var info = { userid: _userId, count: -shopConfig[_productId].price, change_type: 0 }
                        dao.EditTicket(info, function (rusult) {
                            if (rusult) {
                                callback(0);
                            } else {
                                callback(4);
                            }
                        });
                    }
                });
            });
        };

        //保存所有用户
        this.saveAll = function () {
            var self = this;
            this.userList.getAllUserIds().then((userIds) => {
                var users = [];
                userIds.forEach((userId) => {
                    self.userList.getUser(userId).then((user) => {
                        if (user) {
                            users.push(user);
                        }
                    });
                });
                dao.saveAll(users, function (Result) { });
            });
        };

        this.IsPlayerOnline = async function (_userId) {
            if (!_userId) {
                log.info("查询在线,参数错误");
                return 0;
            }
            const exists = await this.userList.hasUser(_userId);
            return exists ? 1 : 0;
        };

        //获得用户当前分数
        this.getPlayerScore = async function (_userId, _callback) {
            if (!_userId) {
                log.info("查询分数,参数错误");
                return -1;
            }

            var sendStr;
            const user = await this.userList.getUser(_userId);

            if (user) {
                if (user.getGameId()) {
                    //游戏在线
                    var gameScoket = ServerInfo.getScoket(user.getGameId());
                    gameScoket.emit('getgold', { userid: _userId });
                    gameScoket.on('getgoldResult', function (msg) {
                        if (msg.Result) {
                            sendStr = JSON.stringify({
                                status: 0,
                                msg: "",
                                data: { score: msg.score, diamond: msg.diamond }
                            });
                            _callback(sendStr);
                        } else {
                            sendStr = '{"status":1,"msg":"在线查询分数失败"}';
                            _callback(sendStr);
                        }
                        gameScoket.removeAllListeners('getgoldResult');
                    })
                } else {
                    //只是在登录服务器
                    sendStr = '{"status":0,"msg":"","data":{"score":' + user.getScore() + ',"diamond":' + user.getDiamond() + '}}';
                    _callback(sendStr);
                }
            } else {
                sendStr = '{"status":1,"msg":"在线查询分数失败"}';
                _callback(sendStr);
            }
        };

        //给在线的用户加分
        this.addgold = async function (_userId, score, callback) {
            if (!_userId) {
                log.info("加分,未登录")
                return 0;
            }

            const user = await this.userList.getUser(_userId);
            if (!user) {
                log.info("加分,未登录")
                return 0;
            } else {
                var gameScoket = ServerInfo.getScoket(user.getGameId());
                var self = this;
                gameScoket.emit('addgold', { userid: _userId, addgold: score });
                gameScoket.on('addgoldResult', function (msg) {
                    if (msg.Result) {
                        var score_before = user.getScore();
                        user.addgold(score);
                        callback(1, score_before);
                    } else {
                        callback(0);
                    }
                    gameScoket.removeAllListeners('addgoldResult');
                });
            }
        }

        //给在线的用户加钻石
        this.adddiamond = async function (_userId, score, callback) {
            if (!_userId) {
                log.info("加分,未登录")
                return 0;
            }

            const user = await this.userList.getUser(_userId);
            if (!user) {
                log.info("加分,未登录")
                return 0;
            } else {
                var gameScoket = ServerInfo.getScoket(user.getGameId());
                var self = this;
                gameScoket.emit('adddiamond', { userid: _userId, adddiamond: score });
                gameScoket.on('adddiamondResult', function (msg) {
                    if (msg.Result) {
                        var diamond_before = user.getDiamond();
                        user.adddiamond(score);
                        callback(1, diamond_before);
                    } else {
                        callback(0);
                    }
                    gameScoket.removeAllListeners('adddiamondResult');
                });
            }
        };

        // 进入游戏
        this.LoginGame = async function (_userId, _sign, gametype, _enCoin) {
            const user = await this.userList.getUser(_userId);
            if (!user) {
                log.err("进入游戏,用户" + _userId + "不存在");
                return { _userId: 0, msg: "用户不存在" };
            }
            if (user.deleteFlag) {
                log.err("进入游戏,用户正在删除" + _userId);
                return { _userId: 0, msg: "用户不存在" };
            }
            //先获得是否在断线列表中****
            var linemsg = this.getLineOutMsg(_userId);
            if (linemsg.Result) {
                if (gametype != linemsg.serverId && parseInt(gametype) != 13900 && parseInt(linemsg.serverId) != 13900) {
                    log.info("用户有在其他游戏中未退出!")
                    log.info(linemsg.serverId)
                    log.info(gametype)
                    return { _userId: 0, msg: "您还在游戏中未退出,请等待上一个牌局结束" };
                }
            }

            if (_enCoin == -1) {
                log.err("进入房间条件出错!")
                return { _userId: 0, msg: "进入房间条件出错!" };
            }
            if (user._sign == _sign) {
                log.info(_userId + " enter game id " + gametype);
                if (gametype != 13900) {
                    user.loginGame(gametype);
                }

                var userInfo = {};
                userInfo._userId = user._userId;
                userInfo._account = user._account;
                userInfo._score = user._score;
                userInfo._nickname = user._nickname;
                userInfo.freeCount = user.freeCount;
                userInfo.LoginCount = user.LoginCount;
                userInfo.LotteryCount = user.LotteryCount;
                userInfo.propList = user._proList;
                userInfo._headimgurl = user._headimgurl;
                userInfo._Robot = user._Robot;
                userInfo._diamond = user._diamond;
                userInfo.is_vip = user.is_vip;
                return userInfo;
            } else {
                log.err("用户进入游戏" + _userId + "密码错误! " + " user sign " + user._sign + " sign " + _sign);
                return { _userId: 0, msg: "密码错误!" };
            }
        };

        this.addLoginList = function (user) {
            return this._loginList.addUser(user)
                .then(() => {
                    log.info("用户添加到登录列表成功");
                })
                .catch((error) => {
                    log.err("添加用户到登录列表失败: " + error.message);
                });
        };

        this.getLoginState = function (useraccount, state) {
            return this._loginList.getLoginState(useraccount, state)
                .then((result) => {
                    return result;
                })
                .catch((error) => {
                    log.err("获取登录状态失败: " + error.message);
                    return false;
                });
        };

        this.deleteLoginList = function (useraccount) {
            return this._loginList.deleteUser(useraccount)
                .then((result) => {
                    if (result) {
                        log.info(`删除用户 ${useraccount} 成功`);
                    }
                    return result;
                })
                .catch((error) => {
                    log.err("删除用户失败: " + error.message);
                    return false;
                });
        };

        // this.updateLogin = async function () {
        //     for (i = 0; i < this._loginList.length; i++) {
        //         if (this._loginList[i] == undefined || this._loginList[i] == null) {
        //             continue;
        //         }
        //         if (!this._loginList[i]._Robot) {
        //             continue;
        //         }

        //         const user = await this.userList.getUser(this._loginList[i].id);
        //         if (user) {
        //             if (user.getGameId()) {
        //                 if (this._loginList[i].state != 4) {
        //                     log.info(this._loginList[i].id + "当前用户游戏" + user.getGameId() + "被强制下线");
        //                     var gameScoket = ServerInfo.getScoket(user.getGameId());
        //                     user._socket.disconnect();
        //                     gameScoket.emit('disconnectUser', { userId: this._loginList[i].id, sysCommand: "loginResult", resultid: 0, kick: 1, msg: 'This account is kicked!' });
        //                     try {
        //                         ServerInfo.getScoket(13900).emit('disconnectUser', { userId: this._loginList[i].id });
        //                         log.info(this._loginList[i].id + " 当前用户游戏 " + user.getGameId() + " 发送断开命令");
        //                     } catch (e) {
        //                         log.info("用户13900服务器断开 try catch server game 819行");
        //                     }
        //                     this._loginList[i].state = 4;
        //                 } else {
        //                     log.info("等待游戏服务器过来删除" + this._loginList[i].id);
        //                     await this.userList.removeUser(this._loginList[i].id);
        //                 }
        //             } else {
        //                 log.info(this._loginList[i].id + "用户只在登录服务器被强制下线");
        //                 if (user._socket.connected) {
        //                     if (this._loginList[i].state == 1) {
        //                         let socket = user._socket;
        //                         var result = { resultid: 0, kick: 1, msg: 'This account is kicked!' };
        //                         socket.emit('loginResult', result);
        //                         socket.disconnect();
        //                         log.info("帐号在登录服务器被踢掉!");
        //                         try {
        //                             ServerInfo.getScoket(13900).emit('disconnectUser', { userId: this._loginList[i].id });
        //                         } catch (e) {
        //                             log.info("server 13900断开失败 disconnectUser");
        //                         }
        //                         this._loginList[i].state = 2;
        //                     }
        //                 } else if (!user.deleteFlag) {
        //                     await this.userList.removeUser(this._loginList[i].id);
        //                     log.info("离线!同时在线: " + (await this.userList.getStats()).players + " 人，机器人数 " + (await this.userList.getStats()).robots);
        //                 }
        //             }
        //         } else {
        //             log.info(this._loginList[i].id + "完全下线了");
        //             var self = this;
        //             this._loginList[i].state = 3;
        //             dao.login(this._loginList[i], this._loginList[i].socket, function (state, rows) {
        //                 if (!state) {
        //                     if (rows && self.getLoginState(rows.Account, 3)) {
        //                         self.deleteLoginList(rows.Account);
        //                         self.addUser(rows, rows.socket, function (rusult) {
        //                             log.info("完成添加");
        //                         });
        //                     } else {
        //                         log.info("状态不为3,又重新登录了");
        //                     }
        //                 } else if (state == 1) {
        //                     var result = { resultid: 0, msg: 'Account or password error,login fail!' };
        //                     socket.emit('loginResult', result);
        //                     log.info("登录失败!", user.userId);
        //                 } else if (state == 2) {
        //                     var result = { resultid: -1, msg: 'This account is disabled!' };
        //                     socket.emit('loginResult', result);
        //                     log.info("登录失败,帐号被停用!");
        //                 }
        //             });
        //         }
        //     }
        // };

        this.updateLogin = function () {
            var self = this;

            // 使用 Promise 方式获取所有登录列表用户
            return this._loginList.getAllUsers()
                .then(function (users) {
                    // 创建一个处理每个用户的 Promise 数组
                    var userPromises = users.map(function (loginUser, index) {
                        return new Promise(function (resolve) {
                            if (loginUser == undefined || loginUser == null) {
                                resolve();
                                return;
                            }
                            if (!loginUser._Robot) {
                                resolve();
                                return;
                            }

                            // 使用立即执行函数处理每个用户
                            (function (loginUser) {
                                self.userList.getUser(loginUser.id)
                                    .then(function (user) {
                                        if (user) {
                                            return self._handleUserWithGame(loginUser, user);
                                        } else {
                                            return self._handleUserOffline(loginUser);
                                        }
                                    })
                                    .then(resolve)
                                    .catch(function (error) {
                                        log.err("处理用户失败: " + error.message);
                                        resolve();
                                    });
                            })(loginUser);
                        });
                    });

                    // 等待所有用户处理完成
                    return Promise.all(userPromises);
                })
                .catch(function (error) {
                    log.err("获取登录列表失败: " + error.message);
                });
        };

        // 处理有游戏的用户
        this._handleUserWithGame = function (loginUser, user) {
            var self = this;

            return new Promise(function (resolve) {
                if (user.getGameId()) {
                    if (loginUser.state != 4) {
                        log.info(loginUser.id + "当前用户游戏" + user.getGameId() + "被强制下线");
                        var gameScoket = ServerInfo.getScoket(user.getGameId());
                        gameScoket.emit('disconnectUser', {
                            userId: loginUser.id,
                            sysCommand: "loginResult",
                            resultid: 0,
                            kick: 1,
                            msg: 'This account is kicked!'
                        });
                        user._socket.disconnect();

                        try {
                            ServerInfo.getScoket(13900).emit('disconnectUser', { userId: loginUser.id });
                            log.info(loginUser.id + " 当前用户游戏 " + user.getGameId() + " 发送断开命令");
                        } catch (e) {
                            log.info("用户13900服务器断开 try catch server game 819行");
                        }

                        // 更新用户状态
                        self._loginList.updateUserState(loginUser.userName, 4)
                            .then(function () {
                                resolve();
                            })
                            .catch(function (error) {
                                log.err("更新用户状态失败: " + error.message);
                                resolve();
                            });
                    } else {
                        log.info("等待游戏服务器过来删除" + loginUser.id);
                        self.userList.removeUser(loginUser.id)
                            .then(function () {
                                resolve();
                            })
                            .catch(function (error) {
                                log.err("删除用户失败: " + error.message);
                                resolve();
                            });
                    }
                } else {
                    self._handleUserWithoutGame(loginUser, user)
                        .then(resolve)
                        .catch(function (error) {
                            log.err("处理无游戏用户失败: " + error.message);
                            resolve();
                        });
                }
            });
        };

        // 处理没有游戏的用户
        this._handleUserWithoutGame = function (loginUser, user) {
            var self = this;

            return new Promise(function (resolve) {
                log.info(loginUser.id + "用户只在登录服务器被强制下线");

                if (user._socket.connected) {
                    if (loginUser.state == 1) {
                        let socket = user._socket;
                        var result = { resultid: 0, kick: 1, msg: 'This account is kicked!' };
                        socket.emit('loginResult', result);
                        socket.disconnect();
                        log.info("帐号在登录服务器被踢掉!");

                        try {
                            ServerInfo.getScoket(13900).emit('disconnectUser', { userId: loginUser.id });
                        } catch (e) {
                            log.info("server 13900断开失败 disconnectUser");
                        }

                        // 更新用户状态
                        self._loginList.updateUserState(loginUser.userName, 2)
                            .then(function () {
                                resolve();
                            })
                            .catch(function (error) {
                                log.err("更新用户状态失败: " + error.message);
                                resolve();
                            });
                    } else {
                        resolve();
                    }
                } else if (!user.deleteFlag) {
                    self.userList.removeUser(loginUser.id)
                        .then(function () {
                            return self.userList.getStats();
                        })
                        .then(function (stats) {
                            log.info("离线!同时在线: " + stats.players + " 人，机器人数 " + stats.robots);
                            resolve();
                        })
                        .catch(function (error) {
                            log.err("删除用户或获取统计失败: " + error.message);
                            resolve();
                        });
                } else {
                    resolve();
                }
            });
        };

        // 处理完全下线的用户
        this._handleUserOffline = function (loginUser) {
            var self = this;

            return new Promise(function (resolve) {
                log.info(loginUser.id + "完全下线了");

                // 更新用户状态
                self._loginList.updateUserState(loginUser.userName, 3)
                    .then(function () {
                        dao.login(loginUser, loginUser.socket, function (state, rows) {
                            if (!state) {
                                if (rows) {
                                    // 检查状态并处理
                                    self._loginList.getLoginState(rows.Account, 3)
                                        .then(function (isState3) {
                                            if (isState3) {
                                                self._loginList.deleteUser(rows.Account)
                                                    .then(function () {
                                                        self.addUser(rows, rows.socket, function (rusult) {
                                                            log.info("完成添加");
                                                            resolve();
                                                        });
                                                    })
                                                    .catch(function (error) {
                                                        log.err("删除用户失败: " + error.message);
                                                        resolve();
                                                    });
                                            } else {
                                                log.info("状态不为3,又重新登录了");
                                                resolve();
                                            }
                                        })
                                        .catch(function (error) {
                                            log.err("检查登录状态失败: " + error.message);
                                            resolve();
                                        });
                                } else {
                                    resolve();
                                }
                            } else if (state == 1) {
                                var result = { resultid: 0, msg: 'Account or password error,login fail!' };
                                loginUser.socket.emit('loginResult', result);
                                log.info("登录失败!", loginUser.id);
                                resolve();
                            } else if (state == 2) {
                                var result = { resultid: -1, msg: 'This account is disabled!' };
                                loginUser.socket.emit('loginResult', result);
                                log.info("登录失败,帐号被停用!");
                                resolve();
                            } else {
                                resolve();
                            }
                        });
                    })
                    .catch(function (error) {
                        log.err("更新用户状态失败: " + error.message);
                        resolve();
                    });
            });
        };

        //兑换电话费
        this.exchange = async function (_userId, _info, io) {
            const user = await this.userList.getUser(_userId);
            if (!user) {
                return;
            }

            if (!user._phoneNo) {
                user._socket.emit('exchangeResult', { Result: 0, msg: "您未绑定手机" });
                return;
            }

            if (!(_info.proCount == 20 || _info.proCount == 50 || _info.proCount == 100)) {
                user._socket.emit('exchangeResult', { Result: 0, msg: "道具数量错误" });
                return;
            }

            var firstValue = 1;
            if (!user._firstexchange) {
                firstValue = 0.5;
            }

            switch (_info.proCount) {
                case 20:
                    _info.deleteCount = Math.floor((_info.proCount * 10) + 0.1);
                    break;
                case 50:
                    _info.deleteCount = Math.floor((_info.proCount * 9.6) + 0.1);
                    break;
                case 100:
                    _info.deleteCount = Math.floor((_info.proCount * 9.2) + 0.1);
                    break;
            }

            if (!user._proList[1] || user._proList[1] < _info.deleteCount) {
                user._socket.emit('exchangeResult', { Result: 0, msg: "道具数量不足" });
                return;
            }

            log.info(_info.deleteCount);
            log.info(user._proList[1]);

            var info = {
                Type: 'A1',
                Account: user._userId,
                PhoneNo: user._phoneNo,
                OrderId: '1',
                CardNum: _info.proCount,
                Key: '89b5b987124d2ec3'
            };

            user._firstexchange = true;

            //调用接口
            //返回后
            //发送兑换结果
            //减掉道具
            //存储兑换记录
            var self = this;
            Post.postExchange(info, function (rusult) {
                if (rusult) {
                    user._proList[1] -= _info.deleteCount;
                    var myNowScore = user._score;
                    user._score -= (cost * firstValue);
                    var NowScore = user._score;

                    var info = { userId: _userId, propId: 1, propCount: -_info.deleteCount, roomid: 0, typeid: 2 };
                    dao.updateProp(info, function (result) { });
                    dao.updateFirstexchange(_userId);

                    var score_change = parseInt(cost * firstValue);
                    var userInfo = {
                        userid: _userId,
                        score_before: myNowScore,
                        score_change: -score_change,
                        score_current: NowScore,
                        change_type: 4,
                        isOnline: true
                    };
                    self.score_changeLogList.push(userInfo);

                    user._socket.emit('exchangeResult', {
                        Result: 1,
                        msg: "兑换成功",
                        deleteCount: -_info.deleteCount,
                        deleteCoin: -(cost * firstValue)
                    });
                    io.sockets.emit('noticeMsg', {
                        nickname: user._nickname,
                        msg: "成功兑换" + _info.proCount + "元电话卡!"
                    });
                }
            });
        };

        //赠送金币
        this.sendCoin = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('sendCoinResult', { Result: 0, msg: "用户不存在" });
                    return;
                }

                if (!user._phoneNo) {
                    _socket.emit('sendCoinResult', { Result: 0, msg: "未绑定手机,不允许赠送" });
                    return;
                }

                if (user.getScore() - _info.sendCoin < 1000) {
                    _socket.emit('sendCoinResult', { Result: 0, msg: "赠送失败,剩余金币不能低于1000" });
                    return;
                }

                // 获取昵称
                dao.checkNickName(_info.sendUserId, async (result, nickName) => {
                    if (result) {
                        // 使用原子操作更新分数
                        const updateResult = await this.userList.atomicUpdateScore(_socket.userId, -_info.sendCoin);

                        if (updateResult.success) {
                            log.info(_socket.userId + "赠送前,金币:" + updateResult.oldScore);
                            log.info(_socket.userId + "赠送金币:" + _info.sendCoin);

                            const info = {
                                userId: _info.sendUserId,
                                winPropId: 0,
                                winPropCount: 0,
                                winScore: _info.sendCoin,
                                type: 1,
                                sendCoinUserId: _socket.userId,
                                nickName: user._nickname
                            };
                            this.sendEmail(info);

                            // 给自己做钱的记录
                            const score_change = parseInt(_info.sendCoin);
                            const NowScore = updateResult.newScore;

                            let userInfo = {
                                userid: _socket.userId,
                                score_before: updateResult.oldScore,
                                score_change: -score_change,
                                score_current: NowScore,
                                change_type: 3,
                                isOnline: true
                            };

                            this.score_changeLogList.push(userInfo);
                            log.info(_socket.userId + "赠送后:" + NowScore);

                            // 获取昵称
                            _socket.emit('sendCoinResult', { Result: 1, score: -_info.sendCoin, msg: "赠送成功" });

                            userInfo = {
                                userid: _socket.userId,
                                getcoinuserid: _info.sendUserId,
                                sendcoin: score_change,
                                nickname: nickName,
                                commission: 0,
                                state: 0
                            };

                            dao.sendcoinlog(userInfo, (code, insertId) => {
                                const emailInfo = {
                                    isread: 0,
                                    title: "转账送礼",
                                    type: 1,
                                    otherId: insertId,
                                    userid: _info.sendUserId,
                                    sendid: _socket.userId,
                                };
                                dao.saveEmail(emailInfo);
                            });
                        } else {
                            _socket.emit('sendCoinResult', { Result: 0, msg: "赠送失败,金钱不足" });
                        }
                    } else {
                        _socket.emit('sendCoinResult', { Result: 0, msg: "未找到该用户" });
                    }
                });
            } catch (error) {
                log.err("sendCoin 错误: " + error.message);
                _socket.emit('sendCoinResult', { Result: 0, msg: "系统错误" });
            }
        };

        // 修改 selectUserIdAndSendCoin 方法
        this.selectUserIdAndSendCoin = function (_socket, _info) {
            dao.getUserId(_info.sendUserName, (code, id) => {
                if (code) {
                    _info.sendUserId = parseInt(id);
                    this.sendCoin(_socket, _info);
                } else {
                    _socket.emit('sendCoinResult', { Result: 0, msg: "未找到该用户" });
                }
            });
        };

        //查询金币记录
        this.selectCoinLog = function (_socket) {
            dao.selectcoinlog(_socket.userId, (code, res) => {
                if (code) {
                    _socket.emit('selectCoinLogResult', { Result: 1, data: res });
                } else {
                    log.info("selectCoinLog失败");
                    // _socket.emit('selectCoinLogResult', {Result: 0, msg: "查询失败"});
                }
            });
        };

        //查询收取金币记录
        this.selectgetCoinLog = function (_socket) {
            dao.selectgetcoinlog(_socket.userId, (code, res) => {
                if (code) {
                    _socket.emit('selectgetcoinlogResult', { Result: 1, data: res });
                } else {
                    log.info("selectCoinLog失败");
                    // _socket.emit('selectCoinLogResult', {Result: 0, msg: "查询失败"});
                }
            });
        };

        this.updateCoinLogState = function (_socket, _info) {
            let state = _info.state;
            let id = _info.id;
            let coin = _info.coin;

            dao.updateCoinLogState(state, id, (code) => {
                if (code) {
                    //发还金币
                    let sendInfo = {
                        sendUserId: _socket.userId,
                        sendCoin: coin,
                        change_type: 11,
                        diamond: 0
                    };
                    this.GameBalance(sendInfo);
                    //发送邮件
                    let emailInfo = {
                        isread: 0,
                        title: "礼物撤回",
                        type: 0,
                        otherId: id,
                        userid: _socket.userId,
                        sendid: 0,
                    };
                    dao.saveEmail(emailInfo);

                    _socket.emit('updateCoinLogStateResult', { Result: 1, data: { state: state, id: id } });
                } else {
                    log.info("updateCoinLogState失败");
                }
            });
        };

        //新邮件推送
        this.haveNewEmail = async function (data) {
            try {
                // 如果用户在线并且在大厅
                switch (data.type) {
                    case 2:
                        const user = await this.userList.getUser(data.userid);
                        if (user && !user.getGameId()) {
                            user._socket.emit('newEmailResult', { Result: 1 });
                        }
                        break;
                    case 999:
                        const allUsers = await this.userList.getAllUsersBasicInfo();
                        for (const userInfo of allUsers) {
                            if (!userInfo.gameId) {
                                const user = await this.userList.getUser(userInfo.userId);
                                if (user) {
                                    user._socket.emit('newEmailResult', { Result: 1 });
                                }
                            }
                        }
                        break;
                }
            } catch (error) {
                log.err("haveNewEmail 错误: " + error.message);
            }
        };

        this.getEmail = function (_socket, _info) {
            if (_info.pageNo <= 0) {
                return;
            }

            //先查系统邮件，再查个人邮件
            let newList = [];
            dao.getSystemEmailNum((code, res) => {
                if (code) {
                    var sysPageNum = Math.floor(res.length / 10);
                    dao.selectSystemEmail(_info.pageNo, (code, res) => {
                        if (code) {
                            for (let i = 0; i < res.length; i++) {
                                newList.push(res[i]);
                            }
                            if (newList.length >= 10) {
                                _socket.emit('getEmailResult', { Result: 1, data: newList });
                                return;
                            }
                        }
                        var lestLen = 10 - newList.length;
                        var lestPageNo;
                        if (lestLen > 0) {
                            lestPageNo = _info.pageNo - sysPageNum;
                        }
                        dao.selectEmail(_socket.userId, lestPageNo, (code, res) => {
                            if (code) {
                                if (lestLen > res.length) {
                                    log.info("pls check email page number!");
                                    return;
                                }
                                for (let i = 0; i < lestLen; i++) {
                                    newList.push(res[i]);
                                }
                            }
                            if (newList.length > 0) {
                                _socket.emit('getEmailResult', { Result: 1, data: newList });
                            } else {
                                _socket.emit('getEmailResult', { Result: 0, msg: "未查到新邮件" });
                            }
                        });
                    });
                }
            });
        };

        this.setEmailRead = function (_socket, _info) {
            dao.setEmailisRead(_info.id, (code, res) => {
                if (code) {
                    _socket.emit('setEmailReadResult', { Result: 1, data: res });
                }
            });
        };
        //领取邮件金币
        this.lqCoin_email = function (_socket, _info) {
            let state = _info.state;
            let id = _info.id;
            let coin = _info.coin;
            dao.updateCoinLogState(state, id, (code) => {
                if (code) {
                    //获得金币
                    let sendInfo = {
                        sendUserId: _socket.userId,
                        sendCoin: coin,
                        change_type: 11,
                        diamond: 0
                    };
                    this.GameBalance(sendInfo);

                    _socket.emit('lqCoin_emailResult', { Result: 1, data: { state: state, id: id } });
                } else {
                    log.info("updateCoinLogState失败");
                }
            });
        };
        //使用点卡
        this.useEXcard = function (_socket, _info) {
            if (this.sendCardList[_socket.userId] && (this.sendCardList[_socket.userId] + _info.cardNum) > 2) {
                _socket.emit('sendcardResult', { Result: 0, msg: "超过当天使用上限" });
                return;
            }
            let userInfo = {
                sendUserId: _socket.userId,
                sendCoin: 0,
                change_type: 13,
                diamond: -_info.cardNum
            };

            dao.checkVip(_info.userId, (code, isVip) => {
                if (code) {
                    if (!isVip) {
                        this.GameBalanceSub(userInfo, (result) => {
                            var data = JSON.parse(result);
                            if (!data.status) {
                                if (this.sendCardList[_socket.userId]) {
                                    this.sendCardList[_socket.userId] += _info.cardNum;
                                } else {
                                    this.sendCardList[_socket.userId] = _info.cardNum;
                                }

                                let userInfo2 = {
                                    sendUserId: _info.userId,
                                    sendCoin: 10000 * _info.cardNum,
                                    change_type: 12,
                                    diamond: 0
                                };
                                this.GameBalance(userInfo2);

                                var userInfolog = {
                                    userid: _socket.userId,
                                    targetId: _info.userId,
                                    coin: 10000 * _info.cardNum,
                                    cardNum: _info.cardNum,
                                };
                                dao.saveCardRecord(userInfolog);
                                _socket.emit('sendcardResult', { Result: 0, msg: "赠送成功" });
                            } else {
                                _socket.emit('sendcardResult', { Result: 0, msg: "赠送失败" });
                            }
                        });
                    } else {
                        _socket.emit('sendcardResult', { Result: 0, msg: "该用户不是普通玩家" });
                    }
                }
            });

        };
        //转赠点卡
        this.sendcard = function (_socket, _info) {
            dao.checkVip(_info.userId, (code, isVip) => {
                if (code) {
                    if (isVip) {
                        let userInfo = {
                            sendUserId: _socket.userId,
                            sendCoin: 0,
                            change_type: 13,
                            diamond: -_info.cardNum
                        };
                        this.GameBalanceSub(userInfo, (result) => {
                            var data = JSON.parse(result);
                            if (!data.status) {
                                let userInfo2 = {
                                    sendUserId: _info.userId,
                                    sendCoin: 0,
                                    change_type: 13,
                                    diamond: _info.cardNum
                                };
                                this.GameBalance(userInfo2);
                                _socket.emit('sendcardResult', { Result: 0, msg: "赠送成功" });
                            } else {
                                _socket.emit('sendcardResult', { Result: 0, msg: "赠送失败" });
                            }
                        });
                    } else {
                        _socket.emit('sendcardResult', { Result: 0, msg: "该用户不是VIP" });
                    }
                }
            });
        };

        //查点卡
        this.cardLog = function (_socket, _info) {
            dao.getCardRecord(_info.userid, (code, res) => {
                if (code) {
                    _socket.emit('cardLogResult', { Result: 1, data: res });
                }
            });
        };

        //检测昵称
        this.checkNickName = async function (_socket, _info) {
            if (parseInt(_info.userId, 10) != _info.userId && _info.userId < 1) {
                _socket.emit('checkNickNameResult', { resultCode: 0, msg: "检测ID错误" });
                return;
            }

            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.err("检测ID:" + _socket.userId + "不存在");
                    return;
                }

                dao.checkNickName(_info.userId, (result, nickName) => {
                    if (result) {
                        _socket.emit("checkNickNameResult", {
                            resultCode: 1,
                            nickName: nickName
                        });
                    } else {
                        _socket.emit("checkNickNameResult", {
                            resultCode: 0,
                            nickName: ""
                        });
                    }
                });
            } catch (error) {
                log.err("checkNickName 错误: " + error.message);
                _socket.emit("checkNickNameResult", {
                    resultCode: 0,
                    nickName: ""
                });
            }
        };

        // 修改 checkNickName2 方法
        this.checkNickName2 = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("checkNickNameResult", { resultCode: 0, nickName: "" });
                    return;
                }

                const self = this;
                dao.checkNickName2(_info.userName, function (result, nickName) {
                    if (result) {
                        _socket.emit("checkNickNameResult", {
                            resultCode: 1,
                            nickName: nickName
                        });
                    } else {
                        _socket.emit("checkNickNameResult", {
                            resultCode: 0,
                            nickName: ""
                        });
                    }
                });
            } catch (error) {
                log.err("checkNickName2 错误: " + error.message);
                _socket.emit("checkNickNameResult", { resultCode: 0, nickName: "" });
            }
        };

        //修改昵称
        this.updateNickName = async function (_socket, _info) {
            const user = await this.userList.getUser(_socket.userId)
            if (!user) {
                log.err("更新用户ID,用户" + _userId + "不存在");
                _socket.emit('updateNickNameResult', { Result: 1, msg: "ID不存在" });
                return;
            }

            //金额
            if (_info.newNickName == "") {
                _socket.emit('updateNickNameResult', { Result: 2, msg: "昵称不能为空" });
                return;
            }
            dao.updateNickName(_socket.userId, _info.newNickName, async function (result, nickName) {
                const user = await this.userList.getUser(_socket.userId)
                if (user) {
                    if (result) {
                        //log.info("发送" + _socket.userId + "检测ID");
                        user._socket.emit("updateNickNameResult", { Result: 0, msg: "修改成功" });
                    } else {
                        user._socket.emit("updateNickNameResult", { Result: 3, msg: "修改失败" });
                    }
                }
            });
        }

        //修改头像
        this.updateHeadUrl = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.err("更新用户ID,用户" + _userId + "不存在");
                    _socket.emit('updateHeadUrlResult', { Result: 1, msg: "ID不存在" });
                    return;
                }

                // 头像
                if (_info.url == "") {
                    _socket.emit('updateHeadUrlResult', { Result: 2, msg: "头像不能为空" });
                    return;
                }

                const self = this;
                dao.updateHeadUrl(_socket.userId, _info.url, function (result, head_url) {
                    if (result) {
                        user._headimgurl = _info.url;
                        user._socket.emit("updateHeadUrlResult", {
                            Result: 0,
                            msg: "修改成功",
                            url: _info.url
                        });
                    } else {
                        user._socket.emit("updateHeadUrlResult", { Result: 3, msg: "修改失败" });
                    }
                });
            } catch (error) {
                log.err("updateHeadUrl 错误: " + error.message);
                _socket.emit('updateHeadUrlResult', { Result: 1, msg: "系统错误" });
            }
        };

        // 修改 getUser 方法
        this.getUser = async function (userId) {
            try {
                return await this.userList.getUser(userId);
            } catch (error) {
                log.err("getUser 错误: " + error.message);
                return null;
            }
        };

        // 修改 addUser 方法
        // this.addUser = async function (userInfo, socket, isRobot = false) {
        //     try {
        //         return await this.userList.addUser(userInfo, socket, isRobot);
        //     } catch (error) {
        //         log.err("addUser 错误: " + error.message);
        //         throw error;
        //     }
        // };

        // 修改 removeUser 方法
        this.removeUser = async function (userId) {
            try {
                return await this.userList.removeUser(userId);
            } catch (error) {
                log.err("removeUser 错误: " + error.message);
                return false;
            }
        };

        // 修改 hasUser 方法
        this.hasUser = async function (userId) {
            try {
                return await this.userList.hasUser(userId);
            } catch (error) {
                log.err("hasUser 错误: " + error.message);
                return false;
            }
        };

        //绑定支付宝
        this.bindZhifubao = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.err("绑定支付宝,用户" + _userId + "不存在");
                    _socket.emit('bindZhifubaoResult', { Result: 1, msg: "ID不存在" });
                    return;
                }

                // 支付宝账号
                // 支付宝真实名字
                if (_info.zhifubao == "") {
                    _socket.emit('bindZhifubaoResult', { Result: 2, msg: "绑定支付宝账号不能为空" });
                    return;
                }

                if (_info.name == "") {
                    _socket.emit('bindZhifubaoResult', { Result: 3, msg: "绑定支付宝实名制名字不能为空" });
                    return;
                }

                if (user._zhifubaoEnd == 1) {
                    _socket.emit('bindZhifubaoResult', { Result: 4, msg: "支付宝与帐号已经终生绑定" });
                    return;
                }

                const self = this;
                dao.bindZhifubao(_socket.userId, _info.zhifubao, _info.name, function (result, nickName) {
                    if (!result) {
                        user._zhifubao = _info.zhifubao;
                        user._zhifubaoName = _info.name;
                        user._socket.emit("bindZhifubaoResult", { Result: 0, msg: "绑定支付宝成功" });
                    } else {
                        if (result == 1) {
                            user._socket.emit("bindZhifubaoResult", {
                                Result: 4,
                                msg: "绑定支付宝已被绑定"
                            });
                        } else if (result == 2) {
                            user._socket.emit("bindZhifubaoResult", {
                                Result: 5,
                                msg: "有订单正在兑换中"
                            });
                        }
                    }
                });
            } catch (error) {
                log.err("bindZhifubao 错误: " + error.message);
                _socket.emit('bindZhifubaoResult', { Result: 1, msg: "系统错误" });
            }
        };

        //绑定银行卡
        this.BankInfo = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.err("绑定银行卡,用户" + _userId + "不存在");
                    _socket.emit('BankInfoResult', { Result: 1, act: _info.act, msg: "ID不存在" });
                    return;
                }

                if (!_info.act) {
                    _socket.emit('BankInfoResult', { Result: 2, act: _info.act, msg: "银行卡操作码不能为空" });
                    return;
                }

                if (_info.act == 1) {
                    if (_info.account == "" || _info.account.length > 30) {
                        _socket.emit('BankInfoResult', { Result: 3, act: _info.act, msg: "添加银行卡账号错误" });
                        return;
                    }

                    if (_info.name == "" || _info.name.length > 30) {
                        _socket.emit('BankInfoResult', { Result: 4, act: _info.act, msg: "添加银行卡实名制名字错误" });
                        return;
                    }

                    if (!_info.bankType) {
                        _socket.emit('BankInfoResult', { Result: 5, act: _info.act, msg: "添加银行卡类型不能为空" });
                        return;
                    }

                    const self = this;
                    dao.addBank(_socket.userId, _info.account, _info.name, _info.bankType, function (result, nickName) {
                        if (result) {
                            user._cardList.push({
                                cardId: result,
                                name: _info.name,
                                bankType: _info.bankType,
                                account: _info.account
                            });

                            user._socket.emit("BankInfoResult", {
                                Result: 0,
                                act: _info.act,
                                cardId: result,
                                msg: "添加银行卡成功"
                            });
                        } else {
                            user._socket.emit("BankInfoResult", {
                                Result: 4,
                                act: _info.act,
                                cardId: 0,
                                msg: "添加银行卡失败"
                            });
                        }
                    });
                } else if (_info.act == 2) {
                    if (_info.cardId == "") {
                        _socket.emit('BankInfoResult', { Result: 3, act: _info.act, msg: "修改卡ID不能为空" });
                        return;
                    }

                    if (_info.account == "" || _info.account.length > 30) {
                        _socket.emit('BankInfoResult', { Result: 3, act: _info.act, msg: "添加银行卡账号错误" });
                        return;
                    }

                    if (_info.name == "" || _info.name.length > 30) {
                        _socket.emit('BankInfoResult', { Result: 4, act: _info.act, msg: "添加银行卡实名制名字错误" });
                        return;
                    }

                    if (!_info.bankType) {
                        _socket.emit('BankInfoResult', { Result: 5, act: _info.act, msg: "修改银行卡类型不能为空" });
                        return;
                    }

                    const self = this;
                    dao.editBank(_socket.userId, _info.account, _info.name, _info.bankType, _info.cardId, function (result, nickName) {
                        if (result) {
                            user._socket.emit("BankInfoResult", {
                                Result: 0,
                                act: _info.act,
                                cardId: _info.cardId,
                                msg: "修改银行卡成功"
                            });
                        } else {
                            user._socket.emit("BankInfoResult", {
                                Result: 4,
                                act: _info.act,
                                cardId: _info.cardId,
                                msg: "修改银行卡失败"
                            });
                        }
                    });
                } else if (_info.act == 3) {
                    if (_info.cardId == "") {
                        _socket.emit('BankInfoResult', { Result: 3, act: _info.act, msg: "删除卡ID不能为空" });
                        return;
                    }

                    const self = this;
                    dao.delBank(_socket.userId, _info.cardId, function (result, nickName) {
                        if (result) {
                            user._socket.emit("BankInfoResult", {
                                Result: 0,
                                act: _info.act,
                                cardId: _info.cardId,
                                msg: "删除银行卡成功"
                            });
                        } else {
                            user._socket.emit("BankInfoResult", {
                                Result: 4,
                                act: _info.act,
                                cardId: _info.cardId,
                                msg: "删除银行卡失败"
                            });
                        }
                    });
                }
            } catch (error) {
                log.err("BankInfo 错误: " + error.message);
                _socket.emit('BankInfoResult', { Result: 1, act: _info.act, msg: "系统错误" });
            }
        };

        //获取银行卡
        this.getBank = async function (_socket) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("getBankResult", { ResultCode: 1, msg: "请先登录" });
                    return;
                }

                const self = this;
                dao.getBank(_socket.userId, function (Result, row) {
                    if (Result) {
                        user._cardList = row;
                        _socket.emit('getBankResult', { ResultCode: 0, data: { bankList: row } });
                    } else {
                        _socket.emit('getBankResult', { ResultCode: 1, data: { bankList: [] } });
                    }
                });
            } catch (error) {
                log.err("getBank 错误: " + error.message);
                _socket.emit("getBankResult", { ResultCode: 1, msg: "系统错误" });
            }
        };

        this.sendEmail = async function (info) {
            try {
                const self = this;
                dao.sendEmail(info, async function (result, idx) {
                    if (result) {
                        const user = await self.userList.getUser(info.userId);
                        if (user) {
                            const prize = {
                                id: idx,
                                propId: info.winPropId,
                                propCount: info.winPropCount,
                                winScore: info.winScore,
                                rankidx: 0,
                                isGetPrize: 0,
                                type: info.type,
                                sendCoinUserId: info.sendCoinUserId,
                                nickName: info.nickName
                            };

                            user._socket.emit("addPrize", prize);

                            // 判断是否已经有此条记录
                            let same = false;
                            if (user && user._prize) {
                                for (let j = 0; j < user._prize.length; j++) {
                                    if (user._prize[j].id == prize.id) {
                                        same = true;
                                        break;
                                    }
                                }
                            }

                            if (!same) {
                                user._prize.push(prize);
                            }
                        }
                    }
                });
            } catch (error) {
                log.err("sendEmail 错误: " + error.message);
            }
        };

        //发送绑定手机验证码
        this.sendbindPhoneNo = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('sendbindPhoneNoResult', { Result: 0, msg: "用户不存在" });
                    return;
                }

                const phone = String(_info.phoneNo);
                if (!_info.phoneNo || phone.length != 11) {
                    _socket.emit('sendbindPhoneNoResult', { Result: 0, msg: "发送失败,手机号码错误" });
                    return;
                }

                const info = {
                    phone: phone,
                    userId: _socket.userId
                };

                const self = this;
                // 需要验证,这个号码是否已经绑定了
                dao.phoneCheck(info, function (ResultCode) {
                    if (ResultCode) {
                        const info = {
                            Type: 'A2',
                            Account: String(_socket.userId),
                            PhoneNo: String(_info.phoneNo),
                            Key: '89b5b987124d2ec3'
                        };

                        info.checkNo = String(user.newCheckNo());
                        self.checkNo[_socket.userId] = { phoneNo: info.PhoneNo, checkNo: info.checkNo };

                        Post.postbindPhone(info, function (rusult) {
                            if (rusult) {
                                _socket.emit('sendbindPhoneNoResult', { Result: 1, msg: "发送成功" });
                            } else {
                                _socket.emit('sendbindPhoneNoResult', { Result: 0, msg: "发送失败" });
                            }
                        });
                    } else {
                        _socket.emit('sendbindPhoneNoResult', { Result: 0, msg: "此手机号码已绑定!" });
                    }
                });
            } catch (error) {
                log.err("sendbindPhoneNo 错误: " + error.message);
                _socket.emit('sendbindPhoneNoResult', { Result: 0, msg: "系统错误" });
            }
        };

        //绑定手机
        this.bindPhone = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('bindPhoneResult', { Result: 0, msg: "用户不存在" });
                    return;
                }

                if (!this.checkNo[_socket.userId]) {
                    _socket.emit('bindPhoneResult', { Result: 0, msg: "未获取验证码" });
                    return;
                }

                if (_info.phoneNo != this.checkNo[_socket.userId].phoneNo) {
                    _socket.emit('bindPhoneResult', { Result: 0, msg: "手机号码错误" });
                    return;
                }

                if (_info.checkNo == "" || _info.checkNo != this.checkNo[_socket.userId].checkNo) {
                    _socket.emit('bindPhoneResult', { Result: 0, msg: "验证码错误" });
                    return;
                }

                const password = String(_info.password);
                const pass = String(_info.password);

                if (!password || password.length < 6) {
                    _socket.emit('bindPhoneResult', { Result: 0, msg: "密码位数不对或密码为空" });
                    return;
                }

                const key_login = "89b5b9871@@@24d2ec3@*&^sexx$%^slxxx";
                const content = password + key_login;
                const md5_sign = crypto.createHash('md5');
                md5_sign.update(content);
                password = md5_sign.digest('hex');

                user.cleanCheckNo();

                const info = { phoneNo: _info.phoneNo, Id: _socket.userId, password: password, pass: pass };
                user.setPhoneNo(this.checkNo[_socket.userId].phoneNo);

                delete this.checkNo[_socket.userId];

                // 数据库更新电话号码
                dao.SetPhoneNo(info, function (ResultCode) {
                    if (ResultCode) {
                        _socket.emit('bindPhoneResult', { Result: 1, msg: "绑定成功" });
                    } else {
                        _socket.emit('bindPhoneResult', { Result: -1, msg: "无法写入数据库" });
                    }
                });
            } catch (error) {
                log.err("bindPhone 错误: " + error.message);
                _socket.emit('bindPhoneResult', { Result: 0, msg: "系统错误" });
            }
        };

        //获取未领奖列表
        this.getSendPrize = async function (_userId, callback) {
            try {
                const user = await this.userList.getUser(_userId);
                if (!user) {
                    callback(0);
                    return;
                }

                const self = this;
                dao.getSendPrize(_userId, async function (result, rows) {
                    const values = [];
                    if (result) {
                        for (let i = 0; i < rows.length; i++) {
                            values.push({
                                id: rows[i].msgId,
                                propId: rows[i].winPropId,
                                propCount: rows[i].winPropCount,
                                winScore: rows[i].winScore,
                                rankidx: rows[i].rankIdx,
                                isGetPrize: rows[i].isGetPrize,
                                type: rows[i].type,
                                sendCoinUserId: rows[i].sendCoinUserId,
                                nickName: rows[i].nickName
                            });
                        }
                    }

                    const currentUser = await self.userList.getUser(_userId);
                    if (currentUser) {
                        currentUser._prize = values;
                    }

                    callback(values);
                });
            } catch (error) {
                log.err("getSendPrize 错误: " + error.message);
                callback(0);
            }
        };

        //每日活动
        this.getdaySendPrize = async function (_userId, callback) {
            try {
                const user = await this.userList.getUser(_userId);
                if (!user) {
                    callback(0);
                    return;
                }

                const self = this;
                dao.getdaySendPrize(_userId, async function (result, rows) {
                    const resultBack = {};
                    const values = [];

                    if (result) {
                        for (let i = 0; i < rows.length; i++) {
                            resultBack.nowday = rows[i].nowday;
                            if (rows[i].day) {
                                if (!rows[i].mark) {
                                    values.push({
                                        id: rows[i].id,
                                        day: rows[i].day,
                                        mark: rows[i].mark
                                    });
                                }
                                if (rows[i].day == resultBack.nowday) {
                                    resultBack.getcoin = -1;
                                }
                            } else {
                                resultBack.getcoin = rows[i].getCoin;
                            }
                        }
                    }

                    const currentUser = await self.userList.getUser(_userId);
                    if (currentUser) {
                        currentUser._dayprize = values;
                    }

                    resultBack.list = values;
                    if (!resultBack.nowday) {
                        resultBack.nowday = 1;
                    }
                    if (!resultBack.getcoin) {
                        resultBack.getcoin = 0;
                    }

                    callback(resultBack);
                });
            } catch (error) {
                log.err("getdaySendPrize 错误: " + error.message);
                callback({ nowday: 1, getcoin: 0, list: [] });
            }
        };

        //领奖
        this.getPrize = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    return;
                }

                const prize = user._prize;
                if (!prize || prize.length <= 0) {
                    _socket.emit('getPrizeResult', { Result: 0, msg: "领奖列表为空" });
                    return;
                }

                let found = false;
                for (let i = 0; i < prize.length; i++) {
                    if (_info.id == prize[i].id) {
                        found = true;
                        if (!prize[i].isGetPrize) {
                            prize[i].isGetPrize = 1;
                            _socket.emit('getPrizeResult', {
                                Result: 1,
                                msg: "成功领取",
                                data: {
                                    winPropId: prize[i].propId,
                                    winPropCount: prize[i].propCount,
                                    winScore: prize[i].winScore
                                }
                            });

                            const myNowScore = user.getScore();
                            log.info(_socket.userId + "领取前" + myNowScore);

                            // 内存添加金币
                            const updateResult = await this.userList.atomicUpdateScore(_socket.userId, prize[i].winScore);

                            if (updateResult.success) {
                                log.info(_socket.userId + "成功领取" + prize[i].winScore);
                                log.info(_socket.userId + "剩余" + updateResult.newScore);

                                // 内存添加道具
                                if (user._proList[prize[i].propId]) {
                                    user._proList[prize[i].propId] += prize[i].propCount;
                                } else {
                                    user._proList[prize[i].propId] = prize[i].propCount;
                                }

                                const info = {
                                    userId: _socket.userId,
                                    propId: prize[i].propId,
                                    propCount: prize[i].propCount,
                                    roomid: 0,
                                    typeid: 3
                                };

                                // 数据库添加道具
                                dao.updateProp(info, function (result) { });

                                // 数据库更新
                                dao.getPrize(_info.id, function (Result) { });

                                // 给自己做钱的记录
                                const score_change = prize[i].winScore;
                                if (prize[i].winScore > 0) {
                                    const userInfo = {
                                        userid: _socket.userId,
                                        score_before: myNowScore,
                                        score_change: score_change,
                                        score_current: updateResult.newScore,
                                        change_type: 6,
                                        isOnline: true
                                    };
                                    this.score_changeLogList.push(userInfo);
                                }
                            }
                            return;
                        } else {
                            _socket.emit('getPrizeResult', { Result: 0, msg: "奖品已经领取" });
                            return;
                        }
                    }
                }

                if (!found) {
                    _socket.emit('getPrizeResult', { Result: 0, msg: "未能找到领奖ID" });
                }
            } catch (error) {
                log.err("getPrize 错误: " + error.message);
                _socket.emit('getPrizeResult', { Result: 0, msg: "系统错误" });
            }
        };

        // 修改 addPrize 方法
        this.addPrize = async function (_info) {
            try {
                const self = this;
                dao.addPrize(_info, async function (result, rows) {
                    if (result) {
                        for (let i = 0; i < rows.length; i++) {
                            // 查看当前ID的玩家是否在线
                            const user = await self.userList.getUser(rows[i].userId);

                            // 如果在线，发送通知并在添加自己领奖列表
                            if (rows[i].rankIdx && user) {
                                const prize = {
                                    id: rows[i].msgId,
                                    propId: rows[i].winPropId,
                                    propCount: rows[i].winPropCount,
                                    winScore: rows[i].winScore,
                                    rankidx: rows[i].rankIdx,
                                    isGetPrize: rows[i].isGetPrize,
                                    type: rows[i].type,
                                    sendCoinUserId: rows[i].sendCoinUserId,
                                    nickName: rows[i].nickName
                                };

                                user._socket.emit("addPrize", prize);

                                // 判断是否已经有此条记录
                                let same = false;
                                if (user && user._prize) {
                                    for (let j = 0; j < user._prize.length; j++) {
                                        if (user._prize[j].id == prize.id) {
                                            same = true;
                                            break;
                                        }
                                    }
                                }

                                if (!same) {
                                    user._prize.push(prize);
                                }
                            }
                        }
                    }
                });
            } catch (error) {
                log.err("addPrize 错误: " + error.message);
            }
        };

        // 修改 getDayPrize 方法
        this.getDayPrize = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('getDayPrizeResult', { Result: 0, msg: "用户不存在" });
                    return;
                }

                const dayprize = user._dayprize;
                if (!dayprize || dayprize.length <= 0) {
                    _socket.emit('getDayPrizeResult', { Result: 0, msg: "领奖列表为空" });
                    return;
                }

                let found = false;
                for (let i = 0; i < dayprize.length; i++) {
                    if (_info.id == dayprize[i].id) {
                        found = true;
                        if (!dayprize[i].mark) {
                            dayprize[i].mark = 1;
                            const propId = activityConfig.dayprize[dayprize[i].day - 1].propId;
                            const propCount = activityConfig.dayprize[dayprize[i].day - 1].propCount;

                            _socket.emit('getDayPrizeResult', {
                                Result: 1,
                                msg: "成功领取",
                                data: { winPropId: propId, winPropCount: propCount }
                            });

                            // 内存添加道具
                            if (user._proList[propId]) {
                                user._proList[propId] += propCount;
                            } else {
                                user._proList[propId] = propCount;
                            }

                            const info = { userId: _socket.userId, propId: propId, propCount: propCount, roomid: 0, typeid: 4 };

                            // 数据库添加道具
                            dao.updateProp(info, function (result) { });

                            // 数据库更新
                            dao.getDayPrize(_info.id, function (Result) { });

                            return;
                        } else {
                            _socket.emit('getDayPrizeResult', { Result: 0, msg: "奖品已经领取" });
                            return;
                        }
                    }
                }

                if (!found) {
                    _socket.emit('getDayPrizeResult', { Result: 0, msg: "未能找到领奖ID" });
                }
            } catch (error) {
                log.err("getDayPrize 错误: " + error.message);
                _socket.emit('getDayPrizeResult', { Result: 0, msg: "系统错误" });
            }
        };



        this.getServerRank = function (_socket, _info) {
            _socket.emit('getServerRankResult', { Result: 1, msg: "", data: this.gameRank[_info.serverId] });
        };

        this.setServerRank = function (_info) {
            this.gameRank[_info.serverId] = _info;
        };

        // 修改 updateOnlineUser 方法
        this.updateOnlineUser = async function () {
            try {
                var self = this;

                var saveList = [];
                for (var k in this.tempuserList) {
                    var userId = this.tempuserList[k]._userId
                    const user = await this.userList.getUser(userId);
                    if (!user) {
                        log.err(this.tempuserList[k]._userId + "不存在");
                    }

                    if (this.tempuserList[k].loginEnd) {
                        saveList.push(this.tempuserList[k]);
                        delete this.tempuserList[k];
                    }
                }
                if (saveList.length > 0) {
                    dao.updateUser(saveList, async function (result) {
                        for (var i = 0; i < result.length; ++i) {
                            var userId = result[i]._userId
                            const user = await self.userList.getUser(userId);
                            if (!user || !user.Robot) {
                                continue
                            }
                            log.info("成功保存,删除用户" + result[i]._userId + " score:" + result[i]._score + " diamond:" + result[i]._diamond);

                            delete self.userList.removeUser(userId);
                            --self.onlinePlayerCount;
                            log.info("离线!同时在线:" + self.onlinePlayerCount + "人")
                        }
                    });
                }
            } catch (error) {
                log.err("pisaveUser 错误: " + error.message);
            }
        };

        // 修改 updateRobotAll 方法
        this.updateRobotAll = async function () {
            try {
                const saveList = [];

                // 获取所有用户ID
                const userIds = await this.userList.getAllUserIds();
                for (const userId of userIds) {
                    const user = await this.userList.getUser(userId);
                    if (user && user._Robot) {
                        saveList.push(user);
                    }
                }

                if (saveList.length) {
                    dao.updateUser(saveList, function (result) { });
                }
            } catch (error) {
                log.err("updateRobotAll 错误: " + error.message);
            }
        };

        //金币排行
        this.getCoinRank = function (_socket) {
            dao.getCoinRank((res) => {
                if (res == 0) {
                    log.info("获取金币排行错误");
                } else {
                    _socket.emit("getCoinRankResult", { ResultCode: 1, result: res });
                }
            });
        };
        //钻石排行
        this.getDiamondRank = function (_socket) {
            dao.getDiamondRank((res) => {
                if (res == 0) {
                    log.info("获取钻石排行错误");
                } else {
                    _socket.emit("getDiamondRankResult", { ResultCode: 1, result: res });
                }
            });
        };

        //商城商品列表
        this.getShopping_List = function (_socket) {
            shopping_dao.selectShopList((res) => {
                if (res == 0) {
                    _socket.emit("getShoppingResult", { ResultCode: 0, msg: "获取商城列表错误" });
                } else {
                    const result = {};
                    for (let i = 0; i < res.length; i++) {
                        if (result[res[i].goodsType]) {
                            result[res[i].goodsType].push(res[i]);
                        } else {
                            result[res[i].goodsType] = [];
                            result[res[i].goodsType].push(res[i]);
                        }
                    }
                    _socket.emit("getShoppingResult", { ResultCode: 1, result: result });
                }
            });
        };
        //获取用户收货信息
        this.getShopPlayerInfo = function (_socket) {
            shopping_dao.selectshouhuoInfo(_socket.userId, (res) => {
                if (res == 0) {
                    log.info("获取用户收货信息失败");
                } else {
                    _socket.emit("getShopPlayerInfoResult", { ResultCode: 1, result: res });
                }
            });
        };
        //更新用户收货信息
        this.updateShopPlayerInfo = function (_socket, _userInfo) {
            shopping_dao.newshouhuoInfo(_socket.userId, _userInfo.adress, _userInfo.userName, _userInfo.phone, (res) => {
                _socket.emit("updateShopPlayerInfoResult", { ResultCode: 1, result: res });
            });
        };
        //申请兑换
        this.requestGetShopItem = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "用户不存在" });
                    return;
                }

                shopping_dao.selectshouhuoInfo(_socket.userId, (res) => {
                    if (res == 0) {
                        _socket.emit("getShopPlayerInfoResult", { ResultCode: 0, msg: "获取用户收货信息失败" });
                    } else {
                        shopping_dao.selectGoodsInfo(_info.id, (res1) => {
                            if (res1 == 0) {
                                _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "获取商品信息失败" });
                                return;
                            }

                            const result = res1[0];
                            if (result.goodsNum < _info.needNum) {
                                _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "商品剩余数量不足" });
                                return;
                            }

                            if (user.getDiamond() < result.goodsPrice * _info.needNum) {
                                _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "印花不足" });
                                return;
                            }

                            const num = result.goodsNum - _info.needNum;
                            shopping_dao.updateGoodsInfo(_info.id, num, (res2) => {
                                if (res2 == 0) {
                                    _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "更新商品信息失败" });
                                } else {
                                    // 使用原子操作更新钻石
                                    this.atomicUpdateDiamond(_socket.userId, -result.goodsPrice * _info.needNum)
                                        .then(updateResult => {
                                            if (updateResult.success) {
                                                user._socket.emit('sendDiamondResult', {
                                                    Result: 1,
                                                    diamond: -result.goodsPrice * _info.needNum,
                                                    msg: "扣钻成功"
                                                });

                                                shopping_dao.newshouhuoRecord(_socket.userId, result.id, 1, result.goodsName, _info.needNum, result.goodsPrice, (res3) => {
                                                    if (res3 == 0) {
                                                        log.info("创建兑换记录失败");
                                                    } else {
                                                        log.info("创建兑换记录成功");
                                                    }
                                                });

                                                _socket.emit("requestGetShopItemResult", { ResultCode: 1 });
                                            } else {
                                                _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "扣钻失败" });
                                            }
                                        });
                                }
                            });
                        });
                    }
                });
            } catch (error) {
                log.err("requestGetShopItem 错误: " + error.message);
                _socket.emit("requestGetShopItemResult", { ResultCode: 0, msg: "系统错误" });
            }
        };
        //获取商城兑换记录
        this.getShouhuoRecord = function (_socket) {
            shopping_dao.selectshouhuoRecord(_socket.userId, (res) => {
                if (res == 0) {
                    _socket.emit("getShouhuoRecordResult", { ResultCode: 0, msg: "未查到兑换记录" });
                } else {
                    _socket.emit("getShouhuoRecordResult", { ResultCode: 1, result: res });
                }
            });
        };
        //获取玩家任务信息
        this.getTaskInfo = function (_socket) {
            redis_dao.queryTask(_socket.userId, (res) => {
                if (res) {
                    const result = JSON.parse(res);
                    const date = new Date().getTime();
                    if (this.isCurrentWeek(result.loginTime)) {
                        if (this.isSameDay(result.loginTime, date)) {
                            _socket.emit("getTaskInfoResult", {
                                ResultCode: 1,
                                result: result,
                                coinList: activityConfig.everyCoin
                            });
                        } else {
                            redis_dao.saveTask(_socket.userId, result, (res) => {
                                if (res) {
                                    _socket.emit("getTaskInfoResult", {
                                        ResultCode: 1,
                                        result: res,
                                        coinList: activityConfig.everyCoin
                                    });
                                }
                            });
                        }
                    } else {
                        redis_dao.saveTask(_socket.userId, null, (res) => {
                            if (res) {
                                _socket.emit("getTaskInfoResult", {
                                    ResultCode: 1,
                                    result: res,
                                    coinList: activityConfig.everyCoin
                                });
                            }
                        });
                    }
                } else {
                    redis_dao.saveTask(_socket.userId, null, (res) => {
                        if (res) {
                            _socket.emit("getTaskInfoResult", {
                                ResultCode: 1,
                                result: res,
                                coinList: activityConfig.everyCoin
                            });
                        }
                    });
                }
            });
        };

        this.isSameDay = function (timeStampA, timeStampB) {
            let dateA = new Date(timeStampA);
            let dateB = new Date(timeStampB);
            return (dateA.setHours(0, 0, 0, 0) == dateB.setHours(0, 0, 0, 0));
        };

        this.isCurrentWeek = function (past) {
            const pastTime = new Date(past).getTime();
            const today = new Date(new Date().toLocaleDateString());
            let day = today.getDay();
            day = day == 0 ? 7 : day;
            const oneDayTime = 60 * 60 * 24 * 1000;
            const monday = new Date(today.getTime() - (oneDayTime * (day - 1)));
            const nextMonday = new Date(today.getTime() + (oneDayTime * (8 - day)));
            if (monday.getTime() <= pastTime && nextMonday.getTime() > pastTime) {
                return true
            } else {
                return false
            }
        };

        //每日登录奖励
        this.getEveryLogin = async function (_socket) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("getEveryLoginResult", { ResultCode: 0, msg: "用户不存在" });
                    return;
                }

                redis_dao.updateEveryLogin(_socket.userId, 2, (res) => {
                    log.info(res);
                    if (res) {
                        // 使用原子操作更新金币
                        this.atomicUpdateScore(_socket.userId, activityConfig.everyCoin[res.num - 1])
                            .then(updateResult => {
                                if (updateResult.success) {
                                    user._socket.emit('sendCoinResult', {
                                        Result: 1,
                                        score: activityConfig.everyCoin[res.num - 1],
                                        msg: "领取成功"
                                    });
                                    _socket.emit("getEveryLoginResult", { ResultCode: 1, result: res });
                                } else {
                                    _socket.emit("getEveryLoginResult", { ResultCode: 0, msg: "领取失败" });
                                }
                            });
                    }
                });
            } catch (error) {
                log.err("getEveryLogin 错误: " + error.message);
                _socket.emit("getEveryLoginResult", { ResultCode: 0, msg: "系统错误" });
            }
        };

        this.score_changeLog = async function () {
            try {
                const saveListTemp = [];
                let ItemTemp;
                let max = 0;

                if (this.score_changeLogList.length > 20) {
                    max = 20;
                } else {
                    max = this.score_changeLogList.length;
                }

                for (let i = 0; i < max; i++) {
                    if (this.score_changeLogList.length > 0) {
                        ItemTemp = this.score_changeLogList.shift();
                        saveListTemp.push(ItemTemp);
                    }
                }

                if (saveListTemp.length > 0) {
                    dao.score_changeLog(saveListTemp);
                }
            } catch (error) {
                log.err("score_changeLog 错误: " + error.message);
            }
        };

        // 修改 diamond_changeLog 方法
        this.diamond_changeLog = async function () {
            try {
                const saveListTemp = [];
                let ItemTemp;
                let max = 0;

                if (this.diamond_changeLogList.length > 20) {
                    max = 20;
                } else {
                    max = this.diamond_changeLogList.length;
                }

                for (let i = 0; i < max; i++) {
                    if (this.diamond_changeLogList.length > 0) {
                        ItemTemp = this.diamond_changeLogList.shift();
                        saveListTemp.push(ItemTemp);
                    }
                }

                if (saveListTemp.length > 0) {
                    dao.diamond_changeLog(saveListTemp);
                }
            } catch (error) {
                log.err("diamond_changeLog 错误: " + error.message);
            }
        };

        this.insertScore_change_log = function (list) {
            for (var i = 0; i < list.length; i++) {
                this.score_changeLogList.push(list[i]);
            }
        };

        this.insertMark = function (list) {
            dao.Insert_Mark(list);
        };
        // this.pre_insertMark = function (list) {
        //     dao.pre_insert_mark(list);
        // };

        //报名
        this.ApplyMatch = async function (_userId, roomid, _socket) {
            try {
                const user = await this.userList.getUser(_userId);
                if (!user) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "用户不存在" });
                    return;
                }

                if (!this.gameRank[roomid]) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "比赛roomid不存在" });
                    return;
                }

                if (this.isMaintain()) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "维护模式,禁止报名!" });
                    return;
                }

                if (this.gameRank[roomid]) {
                    for (let i = 0; i < this.gameRank[roomid].rank.length; i++) {
                        if (this.gameRank[roomid].rank[i].id == _userId) {
                            _socket.emit("applyMatchResult", { ResultCode: 2, msg: "已经报名了" });
                            return;
                        }
                    }
                }

                // 当前房间的报名的费用
                if (user.getScore() < 100) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "金币不足" });
                    return;
                }

                // 比赛时间低于30秒禁止报名
                if (!this.gameRank[roomid].MatchLogin) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "比赛时间低于30秒禁止报名" });
                    return;
                }

                if (!this.gameRank[roomid].ApplyFlag) {
                    _socket.emit("applyMatchResult", { ResultCode: 0, msg: "现在不是比赛时间" });
                    return;
                }

                // 报名成功
                const userInfo = {
                    matchId: this.gameRank[roomid].randIdx,
                    userId: _userId,
                    score: 100,
                    lastTime: new Date(),
                    roomType: roomid,
                    _nickname: user._nickname
                };

                const self = this;
                dao.matchRandKing(userInfo, async function (ResultCode) {
                    // 扣分
                    await self.userList.atomicUpdateScore(_userId, -100);

                    // 通知游戏服务器
                    const gamesocket = ServerInfo.getScoket(roomid);
                    gamesocket.emit("applyMatchResult", userInfo);
                    _socket.emit("applyMatchResult", { ResultCode: 1, msg: "报名成功" });
                });
            } catch (error) {
                log.err("ApplyMatch 错误: " + error.message);
                _socket.emit("applyMatchResult", { ResultCode: 0, msg: "系统错误" });
            }
        };

        this.sendMsg = async function (_userId, _info, io) {
            try {
                const user = await this.userList.getUser(_userId);
                if (!user) {
                    return;
                }

                // 喇叭数量是否够
                if (!user._proList[2]) {
                    user._socket.emit('sendMsgResult', { Result: 0, msg: "道具数量不足" });
                    return;
                }

                // 扣除喇叭
                user._proList[2] -= 1;
                const info = { userId: _userId, propId: 2, propCount: -1 };
                dao.updateProp(info, function (result) { });

                io.sockets.emit('sendMsg', { nickname: user._nickname, msg: _info.msg });
            } catch (error) {
                log.err("sendMsg 错误: " + error.message);
            }
        };

        this.sendMsgToUser = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("sendMsgToUserResult", { ResultCode: 1, msg: "请先登录" });
                    return;
                }

                if (_info.msg.length < 1 || _info.msg.length > 50) {
                    _socket.emit("sendMsgToUserResult", { ResultCode: 1, msg: "字数过长或过短" });
                    return;
                }

                // 找到对方账号
                let isSendEnd = false;
                const targetUser = await this.userList.getUser(_info.userId);

                if (targetUser) {
                    // 对方在线
                    targetUser._socket.emit('sendMsg', {
                        userId: _socket.userId,
                        nickname: user._nickname,
                        msg: _info.msg
                    });
                    isSendEnd = true;
                }

                _socket.emit('sendMsgToUserResult', { ResultCode: 0 });

                const info = {
                    userId: _socket.userId,
                    nickname: user._nickname,
                    toUserId: _info.userId,
                    msg: _info.msg,
                    isSendEnd: isSendEnd
                };

                // 存入数据库
                dao.addcharLog(info, function () { });
            } catch (error) {
                log.err("sendMsgToUser 错误: " + error.message);
                _socket.emit('sendMsgToUserResult', { ResultCode: 1, msg: "系统错误" });
            }
        };

        this.getMsgToUser = async function (_socket) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit("getMsgToUserResult", { ResultCode: 1, msg: "请先登录" });
                    return;
                }

                dao.getcharLog(_socket.userId, function (Result, row) {
                    if (Result) {
                        for (let i = 0; i < row.length; ++i) {
                            row[i].addDate = makeDate(row[i].addDate);
                        }

                        _socket.emit('getMsgToUserResult', { ResultCode: 0, data: { chatList: row } });
                    }
                });
            } catch (error) {
                log.err("getMsgToUser 错误: " + error.message);
                _socket.emit("getMsgToUserResult", { ResultCode: 1, msg: "系统错误" });
            }
        };

        this.sendMsgToUserBySystem = async function (_info) {
            try {
                if (_info.msg.length < 1 || _info.msg.length > 50) {
                    log.info("系统信息字数过长或过短");
                    return;
                }

                // 找到对方账号
                let isSendEnd = false;
                const targetUser = await this.userList.getUser(_info.userId);

                if (targetUser) {
                    // 对方在线
                    targetUser._socket.emit('sendMsg', { userId: 10, nickname: "VIP客服:", msg: _info.msg });
                    isSendEnd = true;
                }

                const info = { userId: 10, toUserId: _info.userId, msg: _info.msg, nickname: "VIP客服", isSendEnd: isSendEnd };

                // 存入数据库
                dao.addcharLog(info, function () { });
            } catch (error) {
                log.err("sendMsgToUserBySystem 错误: " + error.message);
            }
        };


        //是否首次兑换
        this.getfirstexchange = async function (_userId, callback) {
            try {
                const user = await this.userList.getUser(_userId);
                if (!user) {
                    callback(0);
                    return;
                }

                const self = this;
                dao.getfirstexchange(_userId, function (result, rows) {
                    if (result) {
                        user._firstexchange = rows.firstexchange;
                        user._zhifubao = rows.zhifubao;
                        user._zhifubaoName = rows.zhifubaoName;
                        user._zhifubaoEnd = rows.zhifubaoEnd;
                        callback(rows);
                    }
                });
            } catch (error) {
                log.err("getfirstexchange 错误: " + error.message);
                callback(0);
            }
        };

        //获取用户金币数
        this.getUserCoin = function (socket, _info) {
            dao.getUserCoinById(_info.userid, (result, userCoin) => {
                if (result) {
                    let userItem = this.getUser(_info.userid);
                    if (userItem) {
                        //用户在登录服务器
                        log.info("查询用户游戏在线");
                        this.getPlayerScore(_info.userid, (res) => {
                            let data = JSON.parse(res);
                            socket.emit('getPlayerCoinResult', {
                                userCoin: data.data.score,
                                userId: _info.userid,
                                ResultCode: result
                            });
                        });
                    } else {
                        //log.info("查询用户不在线");
                        socket.emit('getPlayerCoinResult', {
                            userCoin: userCoin,
                            userId: _info.userid,
                            ResultCode: result
                        });
                    }
                } else {
                    socket.emit('getPlayerCoinResult', {
                        ResultCode: result,
                        msg: "用户不存在"
                    });
                }
            });
        };
        //查询用户银行密码
        this.getUserBankPwd = function (userid, callback) {
            dao.getBankPwdById(userid, (result, pwd) => {
                if (result) {
                    callback(pwd);
                }
            });
        };

        //修改用户银行密码
        this.updateUserBankPwd = async function (socket, _info) {
            try {
                const user = await this.userList.getUser(socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    socket.emit('updateBankpwdResult', { ResultCode: 0, msg: "用户不在线,无法操作" });
                    return false;
                }

                if (!_info.newPwd || _info.newPwd.length < 6 || _info.newPwd.length > 30) {
                    log.info("密码不能小于6位并不能大于30位");
                    socket.emit('updateBankpwdResult', { ResultCode: 0, msg: "密码不能小于6位并不能大于30位" });
                    return false;
                }

                if (_info.pwd == _info.newPwd) {
                    log.info("新密码不能与旧密码一致");
                    socket.emit('updateBankpwdResult', { ResultCode: 0, msg: "新密码不能与旧密码一致" });
                    return false;
                }

                dao.updateBankPwdById(_info.newPwd, socket.userId, (result) => {
                    socket.emit('updateBankpwdResult', { ResultCode: 1 });
                });
            } catch (error) {
                log.err("updateUserBankPwd 错误: " + error.message);
                socket.emit('updateBankpwdResult', { ResultCode: 0, msg: "系统错误" });
                return false;
            }
        };

        //修改用户银行金币
        this.updateBankScore = async function (socket, _info) {
            try {
                const user = await this.userList.getUser(socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    socket.emit('updateBankScoreResult', { ResultCode: 0, msg: "用户不在线,无法操作" });
                    return;
                }

                const newBscore = user.bankScore + _info.saveCoin;
                dao.updateBankScoreById(newBscore, socket.userId, (result) => {
                    log.info("更新银行分数结果" + result);
                    user.bankScore = newBscore;
                    socket.emit('updateBankScoreResult', {
                        bankScore: user.bankScore,
                        ResultCode: 1
                    });
                });

                const userInfo = {
                    sendUserId: socket.userId,
                    sendCoin: -_info.saveCoin,
                    change_type: 99999,
                    diamond: 0
                };

                if (_info.saveCoin > 0) {
                    this.GameBalanceSub(userInfo, (result) => {
                        log.info(result);
                    });
                } else {
                    this.GameBalance(userInfo);
                }
            } catch (error) {
                log.err("updateBankScore 错误: " + error.message);
                socket.emit('updateBankScoreResult', { ResultCode: 0, msg: "系统错误" });
            }
        };
        //发送API
        this.sendApi = function () {
            for (i = 0; i < this.sendApiList.length; i++) {
                --this.sendApiList[i].sendTime;
                if (!this.sendApiList[i].sendTime) {
                    //发送API
                    //log.info("发送API" + this.sendApiList[i].userid);
                    Post.sendApi(this.sendApiList[i].userid);
                    this.sendApiList.splice(i, 1);
                }
            }
        };

        this.getLv = function (_userId, callback) {
            dao.getWinCoin(_userId, function (result, row) {
                if (result) {
                    callback({ lv: row.lv, exp: row.wincoin, nextExp: activityConfig.wincoinlv[row.lv + 1].value });
                } else {
                    callback({ lv: 0, exp: 0, nextExp: activityConfig.wincoinlv[1].value });
                }
            })
        };

        this.sendCoinServer = function (_info, callback) {
            //log.info(_info)
            var id = parseInt(_info.sendUserId);
            var sendCoin = parseInt(_info.sendCoin);
            if (id <= 0) {
                callback({ Result: 0, msg: "赠送ID不能小于0" });
                return;
            }

            if (id == 3051) {
                callback({ Result: 0, msg: "不能自己赠送自己" });
                return;
            }

            if (sendCoin < 1000) {
                callback({ Result: 0, msg: "赠送金币不能小于1000" });
                return;
            }

            var userItem = this.getUser(id);
            if (userItem) {
                callback({ Result: 0, msg: "对方在游戏中,赠送失败!" });
                return;
            }

            var myuserItem = this.getUser(3051);
            if (myuserItem) {
                callback({ Result: 0, msg: "3051在游戏中,赠送失败!" });
                return;
            }

            //先检查对方金额是否够
            dao.sendcoinServer(id, sendCoin, function (Result) {
                if (Result) {
                    callback({ Result: 1, msg: "赠送成功" });
                } else {
                    callback({ Result: 0, msg: "id:(" + id + ") 金币不足" });
                }
            });

        };

        this.GameBalance = async function (_info, callback) {
            //被赠送id
            var userInfo = {
                userid: _info.sendUserId,
                addgold: _info.sendCoin,
                change_type: _info.change_type,
                adddiamond: _info.diamond
            };
            if (!_info.sendUserId || _info.sendUserId <= 0) {
                log.err(_info.sendUserId + "结算ID不能等于NULL或小于0");
                //log.info("结算ID不能等于NULL或小于0");
                if (callback !== undefined) {
                    callback(0);
                }
            }

            log.info("用户" + _info.sendUserId + "结算");

            var userItem = await this.getUser(_info.sendUserId);
            if (userItem && userItem.getGameId()) {
                //存到表,下次添加
                log.info("结算,在游戏中");
                var youScore = userItem.getScore();
                var youDiamond = userItem.getDiamond();
                if (_info.sendCoin) {
                    dao.tempAddScore(_info.sendUserId, _info.sendCoin, _info.change_type);
                }
                if (_info.diamond) {
                    log.info("========================", _info.diamond, _info.sendUserId);
                    dao.tempAddDiamond(_info.sendUserId, _info.diamond, _info.change_type);
                }

                if (callback !== undefined) {
                    callback(1);
                }
            }

            if (userItem) {
                //用户在登录服务器
                log.info("结算,用户在登录服务器");
                var youScore = userItem.getScore();
                if (_info.sendCoin) {
                    userItem.addgold(_info.sendCoin);
                }
                if (_info.diamond) {
                    userItem.adddiamond(_info.diamond);
                }
                var youNowScore = userItem.getScore();
                var youNowDiamond = userItem.getDiamond();

                if (_info.sendCoin) {
                    userItem._socket.emit('sendCoinResult', { Result: 1, score: _info.sendCoin, msg: "赠送成功" });
                }
                if (_info.diamond) {
                    userItem._socket.emit('sendDiamondResult', { Result: 1, score: _info.diamond, msg: "赠送成功" });
                }

                if (_info.change_type === 0) {//后台充值
                    userItem.totalRecharge += parseInt(_info.sendCoin);
                    dao.updateTotalCharge(_info.sendUserId, userItem.totalRecharge, (res) => {
                        if (res === 1) {
                            userItem._socket.emit('updateVipExpResult', {
                                Result: 1,
                                exp: userItem.totalRecharge,
                                msg: "充值成功"
                            });
                        }
                    });
                }

                //给别人做争的记录
                var userInfolog = {
                    userid: _info.sendUserId,
                    score_before: youScore,
                    score_change: _info.sendCoin,
                    score_current: youNowScore,
                    change_type: _info.change_type,
                    isOnline: true
                };
                this.score_changeLogList.push(userInfolog);
                if (callback !== undefined) {
                    callback(1);
                }
            } else {
                log.info("用户完全不在线修改分数!");

                if (_info.sendCoin) {
                    dao.AddGold(userInfo, function (result_u) {
                        if (result_u) {
                            log.info("结算成功");
                            if (callback !== undefined) {
                                callback(1);
                            }
                        } else {
                            log.err("结算失败,用户[" + userInfo.userid + "]不存在!");
                            if (callback !== undefined) {
                                callback(0);
                            }
                        }
                    });
                }
                if (_info.diamond) {
                    userInfo.adddiamond = _info.diamond;
                    dao.AddDiamond(userInfo, function (result_u) {
                        if (result_u) {
                            log.info("结算成功");
                            if (callback !== undefined) {
                                callback(1);
                            }
                        } else {
                            log.err("结算失败,用户[" + userInfo.userid + "]不存在!");
                            if (callback !== undefined) {
                                callback(0);
                            }
                        }
                    });
                }

                if (_info.change_type === 0) {//后台充值
                    log.info("record userId [" + userInfo.userid + "] recharge date");
                    dao.checkTotalCharge(_info.sendUserId, (res, totalRecharge) => {
                        if (res === 1) {
                            totalRecharge += parseInt(_info.sendCoin);
                            dao.updateTotalCharge(_info.sendUserId, totalRecharge, (res) => {
                                if (res === 1) {
                                    log.info("不在线充值累计", _info.sendUserId);
                                }
                            });
                        }
                    });
                }
            }
        };

        this.GameBalanceSub = async function (_info, callback) {
            //被赠送id
            var userInfo = {
                userid: _info.sendUserId,
                addgold: _info.sendCoin,
                change_type: _info.change_type,
                diamond: _info.diamond
            };
            if (!_info.sendUserId || _info.sendUserId <= 0) {
                log.err(_info.sendUserId + "结算ID不能等于NULL或小于0");
                //log.info("结算ID不能等于NULL或小于0");
                callback('{"status":1,"msg":"结算ID不能等于NULL或小于0"}');
                return;
            }

            log.info("用户" + _info.sendUserId + "结算");

            var userItem = await this.getUser(_info.sendUserId);
            if (userItem && userItem.getGameId()) {
                //存到表,下次添加
                log.info("玩家在游戏中,扣分失败");
                // log.info(_info);
                var youScore = userItem.getScore();
                var youDiamond = userItem.getDiamond();
                if (_info.sendCoin) {
                    dao.tempAddScore(_info.sendUserId, _info.sendCoin, _info.change_type);
                }
                if (_info.diamond) {
                    // log.info("===============================================扣钻石",_info);
                    dao.tempAddDiamond(_info.sendUserId, _info.diamond, _info.change_type);
                }

                callback('{"status":2,"msg":"玩家在游戏中,扣分失败"}');
                return;
            }

            if (userItem) {
                //用户在登录服务器
                log.info("结算,用户在登录服务器");
                var youScore = userItem.getScore();
                var youDiamond = userItem.getDiamond();

                var choice_type = 0
                if (_info.sendCoin) {
                    choice_type = 1
                } else if (_info.diamond) {
                    choice_type = 2
                }

                if (youScore >= Math.abs(_info.sendCoin) && _info.sendCoin && choice_type == 1) {
                    userItem.addgold(_info.sendCoin);
                    var youNowScore = userItem.getScore();

                    userItem._socket.emit('sendCoinResult', { Result: 1, score: _info.sendCoin, msg: "扣分成功" });
                    //给别人做争的记录
                    var userInfolog = {
                        userid: _info.sendUserId,
                        score_before: youScore,
                        score_change: _info.sendCoin,
                        score_current: youNowScore,
                        change_type: _info.change_type,
                        isOnline: true
                    };
                    this.score_changeLogList.push(userInfolog);

                    callback('{"status":0,"msg":"扣分成功"}');
                    return;
                } else if (choice_type == 1) {
                    callback('{"status":3,"msg":"分数不足,扣分失败"}');
                    return;
                }
                if (youDiamond >= Math.abs(_info.diamond) && _info.diamond && choice_type == 2) {
                    userItem.adddiamond(_info.diamond);
                    var youNowScore = userItem.getScore();
                    var youNowDiamond = userItem.getDiamond();
                    log.info(_info.sendUserId)
                    log.info(youNowDiamond)
                    log.info(_info.diamond)
                    // userItem.adddiamond(_info.diamond)

                    userItem._socket.emit('sendDiamondResult', { Result: 1, score: _info.diamond, msg: "扣分成功" });
                    // //给别人做争的记录
                    // var userInfolog = {
                    //     userid: _info.sendUserId,
                    //     score_before: youScore,
                    //     score_change: _info.sendCoin,
                    //     score_current: youNowScore,
                    //     change_type: _info.change_type,
                    //     isOnline: true
                    // };
                    // this.score_changeLogList.push(userInfolog);

                    callback('{"status":0,"msg":"扣分成功"}');
                    return;
                } else {
                    callback('{"status":3,"msg":"分数不足,扣分失败"}');
                    return;
                }

            } else {
                log.info("用户完全不在线修扣分!");
                if (_info.sendCoin) {
                    dao.AddGoldSub(userInfo, function (result_u) {
                        if (result_u) {
                            log.info("扣分成功");
                            callback('{"status":0,"msg":"扣分成功"}');
                            return;
                        } else {
                            log.err("扣分失败!");
                            callback('{"status":3,"msg":"分数不足,扣分失败"}');
                            return;
                        }
                    });
                }
                if (_info.diamond) {
                    dao.AddDiamondSub(userInfo, function (result_u) {
                        if (result_u) {
                            log.info("扣分成功");
                            callback('{"status":0,"msg":"扣分成功"}');
                            return;
                        } else {
                            log.err("扣分失败!");
                            callback('{"status":3,"msg":"分数不足,扣分失败"}');
                            return;
                        }
                    });
                }

            }
        };

        this.getScoreChange = function (_socket, _info) {
            dao.selectScoreChangeLog(_info.userid, (code, res) => {
                if (code) {
                    _socket.emit('getScoreChangeResult', { Result: 1, data: res });
                } else {
                    _socket.emit('getCoinLogResult', { Result: 0, msg: "未查到该用户相关记录" });
                }
            });
        };

        //查询金币记录2
        this.getCoinLog = function (_socket, _info) {
            dao.selectcoinlog(_info.userid, (code, res) => {
                if (code) {
                    _socket.emit('getCoinLogResult', { Result: 1, data: res });
                } else {
                    log.info("selectCoinLog失败");
                    _socket.emit('getCoinLogResult', { Result: 0, msg: "未查到该用户相关记录" });
                }
            });
        };

        //断线通知
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                // log.info("----------------------------添加lineOutSet")
                // log.info(_info.serverId)
                // log.info(this.lineOutList)
                if (parseInt(_info.serverId) != 13900) {
                    // log.info("----------------------------进来了")
                    this.lineOutList[_info.userId] = {
                        gameId: _info.gameId,
                        serverId: _info.serverId,
                        tableId: _info.tableId,
                        seatId: _info.seatId,
                        tableKey: _info.tableKey
                    }
                    // log.info(_info)
                    // dao.saveLineOut(_info.userId)
                }

                log.info(this.lineOutList[_info.userId]);
            } else {
                //移除
                // dao.deleteLineOut(_info.userId)
                delete this.lineOutList[_info.userId];
            }
        };

        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return { Result: 0 };
            }
        };


        this.checkData = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    _socket.emit('changeOfficialResult', { ResultCode: 1, msg: "用户不在线,无法操作" });
                    return false;
                }

                if (!_info.newAccount || _info.newAccount.length < 4 || _info.newAccount.length > 30) {
                    log.info("用户名不能小于4位并不能大于30位");
                    _socket.emit('changeOfficialResult', { ResultCode: 2, msg: "用户名不能小于4位并不能大于30位" });
                    return false;
                }

                const pattern = new RegExp("^[A-Za-z0-9]+$");
                if (!pattern.test(_info.newAccount)) {
                    log.info("账号不能有特殊符号");
                    _socket.emit('changeOfficialResult', { ResultCode: 5, msg: "账号不能有特殊符号" });
                    return false;
                }

                if (!_info.password || _info.password.length < 6 || _info.password.length > 30) {
                    log.info("密码不能小于6位并不能大于30位");
                    _socket.emit('changeOfficialResult', { ResultCode: 3, msg: "密码不能小于6位并不能大于30位" });
                    return false;
                }

                if (user._official) {
                    log.info("用户已经转正,无法再次转正");
                    _socket.emit('changeOfficialResult', { ResultCode: 4, msg: "用户已经转正,无法再次转正" });
                    return false;
                }

                return true;
            } catch (error) {
                log.err("checkData 错误: " + error.message);
                _socket.emit('changeOfficialResult', { ResultCode: 1, msg: "系统错误" });
                return false;
            }
        };


        this.changeOfficial = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('changeOfficialResult', { ResultCode: 1, msg: "用户不存在" });
                    return;
                }

                _info.userId = _socket.userId;
                const key = "89b5b987124d2ec3";
                const content = _info.newAccount + _info.password + key;
                _info.p = _info.password;
                const md5 = crypto.createHash('md5');
                md5.update(content);
                _info.password = md5.digest('hex');

                const self = this;
                dao.changeOfficial(_info, function (result) {
                    if (result) {
                        // 修改内存数据
                        user._official = true;
                        user._p = _info.p;
                        user._account = _info.newAccount;

                        _socket.emit('changeOfficialResult', { ResultCode: 0, msg: "转正成功" });
                    } else {
                        _socket.emit('changeOfficialResult', { ResultCode: 5, msg: "用户名已经存在,修改后重试" });
                    }
                });
            } catch (error) {
                log.err("changeOfficial 错误: " + error.message);
                _socket.emit('changeOfficialResult', { ResultCode: 1, msg: "系统错误" });
            }
        };

        this.checkDataPassword = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    _socket.emit('updatePasswordResult', { ResultCode: 1, msg: "用户不在线,无法操作" });
                    return false;
                }

                if (!_info.password || _info.password.length < 6 || _info.password.length > 30) {
                    log.info("密码不能小于6位并不能大于30位");
                    _socket.emit('updatePasswordResult', { ResultCode: 2, msg: "密码不能小于6位并不能大于30位" });
                    return false;
                }

                if (!_info.oldPassword || _info.oldPassword.length < 6 || _info.oldPassword.length > 30) {
                    log.info("旧密码不能小于6位并不能大于30位");
                    _socket.emit('updatePasswordResult', { ResultCode: 3, msg: "旧密码不能小于6位并不能大于30位" });
                    return false;
                }

                if (_info.password == _info.oldPassword) {
                    log.info("新密码不能与旧密码一致");
                    _socket.emit('updatePasswordResult', { ResultCode: 4, msg: "新密码不能与旧密码一致" });
                    return false;
                }

                // 是否已经转正
                if (!user._official) {
                    log.info("先转正后,再改密码");
                    _socket.emit('updatePasswordResult', { ResultCode: 5, msg: "先转正后,再改密码" });
                    return false;
                }

                if (_info.oldPassword != user._p) {
                    log.info("旧密码不正确");
                    _socket.emit('updatePasswordResult', { ResultCode: 6, msg: "旧密码不正确" });
                    return false;
                }

                return true;
            } catch (error) {
                log.err("checkDataPassword 错误: " + error.message);
                _socket.emit('updatePasswordResult', { ResultCode: 1, msg: "系统错误" });
                return false;
            }
        };

        this.updatePassword = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('updatePasswordResult', { ResultCode: 1, msg: "用户不存在" });
                    return;
                }

                const key = "89b5b987124d2ec3";
                const content = user._account + _info.password + key;
                const md5 = crypto.createHash('md5');
                md5.update(content);

                const info = { accountname: user._account, pwd: md5.digest('hex'), p: _info.password };

                const self = this;
                dao.SetPassword(info, function (result) {
                    if (result) {
                        user._p = _info.password;
                        _socket.emit('updatePasswordResult', { ResultCode: 0, msg: "密码修改成功", data: { ps: _info.password } });
                    } else {
                        _socket.emit('updatePasswordResult', { ResultCode: 5, msg: "数据库操作失败" });
                    }
                });
            } catch (error) {
                log.err("updatePassword 错误: " + error.message);
                _socket.emit('updatePasswordResult', { ResultCode: 1, msg: "系统错误" });
            }
        };

        this.scoreOut = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    _socket.emit('scoreOutResult', { ResultCode: 1, msg: "用户不在线,无法操作" });
                    return false;
                }

                if (_info.score < 5000) {
                    log.info("兑奖数量出错!");
                    _socket.emit('scoreOutResult', { ResultCode: 2, msg: "最少兑奖50" });
                    return false;
                }

                if (_info.score % 100 != 0) {
                    log.info("兑换金额必须是100的倍数");
                    _socket.emit('scoreOutResult', { ResultCode: 7, msg: "兑换金额必须是100的倍数" });
                    return false;
                }

                const score = user.getScore();

                if (score - _info.score < 800) {
                    log.info("至少保留10!");
                    _socket.emit('scoreOutResult', { ResultCode: 5, msg: "至少保留8" });
                    return false;
                }

                if (!(_info.type == 0 || _info.type == 1)) {
                    log.err("兑换类型不对!");
                    _socket.emit('scoreOutResult', { ResultCode: 6, msg: "兑换类型不对!" });
                    return false;
                }

                let cardId = -1;
                let cardInfo = null;

                if (_info.type == 0) {
                    if (!user._zhifubao) {
                        log.info("请先绑定支付宝!");
                        _socket.emit('scoreOutResult', { ResultCode: 3, msg: "请先绑定支付宝" });
                        return false;
                    }

                    const myDate = new Date();
                    const out_trade_no = String(myDate.getFullYear()) + String(myDate.getMonth() + 1) + String(myDate.getDate()) + String(myDate.getTime()) + String(this.todayId);

                    if (this.todayId > 10000) {
                        this.todayId = 0;
                    }

                    this.todayId++;

                    const userInfo = { sendUserId: _socket.userId, sendCoin: -_info.score, change_type: 2 };
                    const self = this;

                    this.GameBalanceSub(userInfo, function (_sendStr) {
                        const data = JSON.parse(_sendStr);
                        if (!data.status) {
                            // 记录订单
                            // 保存兑换记录
                            _socket.emit('scoreOutResult', { ResultCode: 0, msg: "兑奖成功" });

                            const socreOut_userInfo = {
                                sendUserId: _socket.userId,
                                sendCoin: _info.score,
                                cardType: _info.type,
                                cardId: cardId,
                                out_trade_no: out_trade_no,
                                zfb_account: user._zhifubao,
                                zfb_name: user._zhifubaoName,
                                tax: 0
                            };

                            if (_info.score <= 10000) {
                                socreOut_userInfo.tax = 300;
                            } else {
                                socreOut_userInfo.tax = _info.score * 0.02;
                            }

                            socreOut_userInfo.coin = ((_info.score - socreOut_userInfo.tax) / 100).toFixed(2);

                            dao.socreOut(socreOut_userInfo, function (result) {
                                if (result) {
                                    // 立即到账逻辑...
                                } else {
                                    log.err("创建兑换订单出错");
                                }
                            });
                        }
                    });
                } else if (_info.type == 1) {
                    // 银行卡兑换逻辑...
                }
            } catch (error) {
                log.err("scoreOut 错误: " + error.message);
                _socket.emit('scoreOutResult', { ResultCode: 1, msg: "系统错误" });
                return false;
            }
        };

        this.updateScoreOut = function (out_trade_no, flag, remark, callback) {
            var self = this;
            dao.updateScoreOut(out_trade_no, flag, remark, function (result, row) {
                if (!result && flag == 1) {
                    log.info(row)
                    var info = { userId: row.userId, msg: '你的兑换已经处理完毕,请查看银行卡或支付宝账单,处理时间(' + makeDate(row.outDate) + ')' }
                    self.sendMsgToUserBySystem(info);
                }
                callback(result);
            })

            //你的兑换已经处理完毕,请查看支付宝账单,处理时间(2017-06-22 13:43)

        };

        this.updateCharLog = async function (_socket, idList, callback) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    log.info("用户不在线,无法操作");
                    _socket.emit('updateCharLogResult', { ResultCode: 1, msg: "用户不在线,无法操作" });
                    return false;
                }

                if (!idList || idList.length <= 0) {
                    _socket.emit('updateCharLogResult', { ResultCode: 2, msg: "更新ID为空" });
                    return;
                }

                dao.updateCharLog(_socket.userId, idList, function (result, row) {
                    if (result) {
                        _socket.emit('updateCharLogResult', { ResultCode: 0, msg: "更新成功" });
                    } else {
                        _socket.emit('updateCharLogResult', { ResultCode: 3, msg: "更新失败" });
                    }
                });
            } catch (error) {
                log.err("updateCharLog 错误: " + error.message);
                _socket.emit('updateCharLogResult', { ResultCode: 1, msg: "系统错误" });
            }
        };
        this.sendNotice = function (io) {
            var noticeConfig = updateConfig.getNoticeConfig();
            io.sockets.emit('noticeMsg', { msg: noticeConfig.msg, date: noticeConfig.date });
            //io.sockets.emit('noticeMsg',{nickname:Robotname[idx].nickname,msg:"成功兑换20元电话卡!"});
        };

        this.PostCoin = function () {
            //var nowDate = new Date();
            var nowDate = new Date();
            nowDate.setMinutes(nowDate.getMinutes() - 3, nowDate.getSeconds(), 0);
            nowDate = makeDate(nowDate);
            var self = this;
            dao.getScoreOut(nowDate, function (result, row) {
                if (result) {
                    var info = {
                        out_biz_no: row.out_trade_no,
                        payee_account: row.zfb_account,
                        amount: row.coin,
                        payee_real_name: row.zfb_name,
                        Key: '89b5b987124d2ec3'
                    };
                    //slog.info(info)
                    Post.postExchangeCoin(info, function (post_result, remark) {
                        if (!post_result) {
                            //告知玩家,支付宝帐号有错误，并退款
                            var info = { userId: row.userId, msg: '你的支付宝有误,重新绑定后,再试!' }
                            self.sendMsgToUserBySystem(info);
                            var userInfo = { sendUserId: row.userId, sendCoin: row.score, change_type: 2 };
                            self.GameBalance(userInfo);
                            remark = remark.substring(0, 50);
                            post_result = 2;
                        }
                        self.updateScoreOut(row.out_trade_no, post_result, remark, function (result) {
                            switch (result) {
                                case 0:
                                    log.info("兑奖更新成功");
                                    break;
                                case 1:
                                    log.err("兑奖更新失败,找不到订单");
                                    break;
                            }
                        });
                    });

                } else {
                    //log.info("暂未有数据");
                }
            })
        };

        //proTypeId,addProCount,userId,roomid,typeid
        this.pro_change = async function (_info) {
            try {
                const user = await this.userList.getUser(_info.userId);
                if (!user) {
                    log.err("用户不存在,无法操作");
                    return;
                }

                // 需要判断道具是否存在;
                if (!user._proList[_info.proTypeId]) {
                    user._proList[_info.proTypeId] = 0;
                }

                if (user._proList[_info.proTypeId] + _info.addProCount < 0) {
                    log.err("道具不足,无法操作");
                    return;
                }

                user._proList[_info.proTypeId] += _info.addProCount;
                const info = {
                    userId: _info.userId,
                    propId: _info.proTypeId,
                    propCount: _info.addProCount,
                    roomid: _info.roomid,
                    typeid: _info.typeid
                };

                dao.updateProp(info, function (result) { });
            } catch (error) {
                log.err("pro_change 错误: " + error.message);
            }
        };

        //发送信息给GM
        this.sendMsgToGM = async function (_socket, _info) {
            try {
                const user = await this.userList.getUser(_socket.userId);
                if (!user) {
                    _socket.emit('sendMsgToGMResult', { ResultCode: 1, msg: "用户不存在" });
                    return;
                }

                redis_send_and_listen.send_msg("sendMsgToGM", {
                    user_id: _socket.userId,
                    user_name: user._nickname,
                    msg: _info.msg,
                    gm_id: _info.gm_id,
                });

                const gm_socket = this.gm_socket[_info.gm_id];
                if (gm_socket) {
                    gm_socket.emit('sendMsgToGM', {
                        user_id: _socket.userId,
                        user_name: user._nickname,
                        msg: _info.msg,
                        gm_id: _info.gm_id,
                    });
                }

                _socket.emit('sendMsgToGMResult');
            } catch (error) {
                log.err("sendMsgToGM 错误: " + error.message);
                _socket.emit('sendMsgToGMResult', { ResultCode: 1, msg: "系统错误" });
            }
        };
        // 修改 updateUserGameState 方法
        this.updateUserGameState = async function (userId, gameId, roomId, tableId, seatId) {
            try {
                return await this.userList.updateUserGameState(userId, gameId, roomId, tableId, seatId);
            } catch (error) {
                log.err("updateUserGameState 错误: " + error.message);
                return false;
            }
        };

        // 修改 resetUserGameState 方法
        this.resetUserGameState = async function (userId) {
            try {
                return await this.userList.resetUserGameState(userId);
            } catch (error) {
                log.err("resetUserGameState 错误: " + error.message);
                return false;
            }
        };

        // 修改 atomicUpdateScore 方法
        this.atomicUpdateScore = async function (userId, delta) {
            try {
                return await this.userList.atomicUpdateScore(userId, delta);
            } catch (error) {
                log.err("atomicUpdateScore 错误: " + error.message);
                return { success: false, error: error.message };
            }
        };

        // 修改 atomicUpdateDiamond 方法
        this.atomicUpdateDiamond = async function (userId, delta) {
            try {
                return await this.userList.atomicUpdateDiamond(userId, delta);
            } catch (error) {
                log.err("atomicUpdateDiamond 错误: " + error.message);
                return { success: false, error: error.message };
            }
        };

        //运行初始化
        this.init();
    };


    if (_gameinfo) {
        return { getInstand: _gameinfo }
    } else {
        log.info("####create game!####");
        _gameinfo = new Game();
        return { getInstand: _gameinfo }
    }

}();

function es6_set(arr) {
    //es6 数组去重
    return Array.from(new Set(arr));
}

function makeDate(date) {

    try {

        var newDate = new Date(date);
        //在小于10的月份前补0
        var month = eval(newDate.getMonth() + 1) < 10 ? '0' + eval(newDate.getMonth() + 1) : eval(newDate.getMonth() + 1);
        //在小于10的日期前补0
        var day = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
        //在小于10的小时前补0
        var hours = newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours();
        //在小于10的分钟前补0
        var minutes = newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes();
        //在小于10的秒数前补0
        var seconds = newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds();
        //拼接时间
        var stringDate = newDate.getFullYear() + '-' + month + '-' + day + " " + hours + ":" + minutes + ":" + seconds;
    } catch (e) {
        var stringDate = "0000-00-00 00:00:00";
    } finally {
        return stringDate;
    }

};

module.exports = GameInfo;

//监听gm发送来的消息
redis_send_and_listen.client_1.on("message", function (channel, message) {
    log.info("------------------------------server接收到信息了");
    log.info("channel" + channel);
    log.info("message" + message);
    var message = JSON.parse(message);
    if (channel == "GMsendMsgToUser") {
        const user = GameInfo.getInstand.userList.getUser(message.user_id);
        if (user) {
            var send_socket = user._socket;
            send_socket.emit("GMsendMsg", { gm_id: message.gm_id, msg: message.msg })
        }
    }
    if (channel == "DDZBSC_START") {
        if (parseInt(message.start)) {
            log.info("斗地主比赛场开始")
            GameInfo.getInstand.landload_race_is_start = true;
            GameInfo.getInstand.landload_race_dict = message

        } else {
            log.info("斗地主比赛场关闭")
            GameInfo.getInstand.landload_race_is_start = false;
            GameInfo.getInstand.landload_race_dict = {}
        }
    }
});
